Column values in Grid View not showing in order - C# - c#

I am having some trouble with this code, I am passing rows from one Grid View to another, but the Grid View is not displaying the data in order.
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class PuntoVenta : Page
{
DataTable dtband = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtbind = new DataTable();
dtbind.Columns.Add("Id");
dtbind.Columns.Add("Qnt");
dtbind.Columns.Add("Unit");
dtbind.Columns.Add("Name");
dtbind.Columns.Add("Rel");
dtbind.Columns.Add("Price");
dtbind.Columns.Add("Class");
Session["ss"] = dtbind;
}
}
protected void GridViewA_SelectedIndexChanged(object sender, EventArgs e) {
dtband = (DataTable)Session["ss"];
DataRow dataRow;
dataRow = dtband.NewRow();
int i2 = 0;
for (int i = 0; i < dataRow.Table.Columns.Count; i++)
{
dataRow[i] = GridViewA.SelectedRow.Cells[i2].Text;
i2++;
}
dtband.Rows.Add(dataRow);
GridViewB.DataSource = dtband;
GridViewB.DataBind();
}
}
When I run the code, The GridViewB is populated but its first Column is empty, furthermore, the values that should be displayed in the first column, are displayed in the second column.

You can set DiplayIndex property of Gridview Column,
//Here 1 is index of desired column
datagridview1.Columns["ColumnName"].DisplayIndex = 1;
Add below code in your application
dtbind.Columns.Add("Id");
dtbind.Columns["Id"].DisplayIndex = 0;
dtbind.Columns.Add("Qnt");
dtbind.Columns["Qnt"].DisplayIndex = 1;
//Like onwards
For more info on DisplayIndex property refer This Link

Related

Change text in specific row in gridview using checkbox

I want to change a specific text in my gridview here's an image below:
Example if I click the checkbox button the specific row "Status" text is change to "Validated".
This is my aspx code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MSSQLConnector;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class TeacherPage : System.Web.UI.Page
{
private MSConnector connector = new MSConnector();
private DataSet SubjectlistData;
private DataTable SubjectlistTable;
string query = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate The Select Tag with Subjects
SubjectList.DataSource = Session["TeacherSubjectList"];
SubjectList.DataTextField = "CourseNo";
SubjectList.DataValueField = "CourseNo";
SubjectList.DataBind();
}
}
}
protected void TeacherSubjects_Click(object sender, EventArgs e)
{
string getText = SubjectList.SelectedItem.Text;
//Connection String
connector.ConnectionString = "Data Source=keith;Initial Catalog=SAD;Integrated Security=True";
query = "select StudentID,CourseNo,CourseDescription,Units,Day,StartTime,EndTime,Room,Instructor,Amount,Status from assessmentform where CourseNo = '" + getText + "'";
SubjectlistData = connector.ExecuteQuery(query);
SubjectlistTable = SubjectlistData.Tables[0];
//Add a colum check row
SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));
Session["ValidateSubject"] = SubjectlistTable;
Response.Redirect("ValidateSubjectTeacher.aspx");
}
I add a checkbox in my row to my gridview using this:
//Add a colum check row
SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));
Session["ValidateSubject"] = SubjectlistTable;
I pass my gridview using session to another page,
its aspx code behind ValidatePage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class ValidateSubjectTeacher : System.Web.UI.Page
{
CheckBox check = new CheckBox();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ValidateSubject"] == null)
{
Response.Redirect("TeacherPage.aspx", true);
}
if (!IsPostBack)
{
ValidateSubject.DataSource = Session["ValidateSubject"];
ValidateSubject.DataBind();
}
//I add my checkbox in the last row using this
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox;
check.Enabled = true;
}
}
protected void ValidateSubject_Click(object sender, EventArgs e)
{
if(check.Checked)
{
//This condition here is I want to change the Status when check to validated.
}
}
}
in my code behind using session I bind all the data in DataTable(FirstPage);
DataSet ds = connector.ExecuteQuery(query);
DataTable dt = dt.Table[0];
dt.DataBind();
Session["SubjectList"] = dt;
You can use the NamingContainer property like this:-
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk= (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give you row
grvRow.Cells[10].Text = "Validated"; //Updated the cell text in that row.
//Or if Status is a control like label then //
Label StatusLabel = (Label)grvRow.FindControl("StatusLabel");
StatusLabel.Text = "Validated";
}
Alternatively, you can also use the RowDataBound event.
Update:
Since you are binding the grid with directly i.e. AutoGenerateColumns set as true, you will have to attach the event handler of checkbox programmatically as well like this:-
//I add my checkbox in the last row using this
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox;
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event
check.AutoPostBack = true; //Set the AutoPostBack property to true
}
Now, in your event first find the row with the help of checkbox, then update the Status column like this:-
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk= (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give you row
if(chk.Checked)
{
grvRow.Cells[10].Text = "Validated";
}
}
You can use an Extension Method like this:
public static class myExtensionsMethods
{
public static void validateRow(this object sender)
{
int columnIndex = 10;
GridViewRow myRow = ((Control)sender).Parent as GridViewRow;
myRow.Cells[columnIndex].Text = "Validated";
}
}
The extension method will allow you to call it in this way
protected void ValidateSubject_Click(object sender, EventArgs e)
{
if (check.Checked)
{
sender.validateRow();
}
}

Filtering data row value in column DataGridView with value inside two textbox

thank you for your time.
I'm trying to write the program to filter the value from CSV file. I have three textbox and one datagridview in my form.
So far i managed to parse the CSV into the DataGridView. The problem occur when i trying to filter the value inside the first column by using two value in textbox.
So far, i just managed to selected the row with value given in the Textbox. How can i possibly to filter the datagridview like below:-
Textbox1 value < value in column > Textbox2 value
This is example of my csv files:-
Northing,Easting,Result
645789.900,578778.982,6.78
645782.892,578767.289,5.54
645801.435,579213.430,6.78
645804.156,579445.670,5.79
645980.188,582544.389,8.90
645983.456,582667.344,8.79
646590.253,584788.212,7.60
646800.789,585690.312,2.50
646909.452,585780.212,4.30
647900.323,585890.345,6.89
This is code i using so far:-
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Linq;
using System.ComponentModel;
using DgvFilterPopup;
namespace ZoningParameter
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void BtnSelectClick(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
// Insert code to read the stream here.
tbxSelectFile.Text = openFileDialog1.FileName;
myStream.Close();
}
}
}
void BtnCancelClick(object sender, EventArgs e)
{
tbxSelectFile.Text = null;
}
void BtnGenerateClick(object sender, EventArgs e)
{
// get all lines of csv file
string[] str = File.ReadAllLines(tbxSelectFile.Text);
// create new datatable
DataTable dt = new DataTable();
// get the column header means first line
string[] temp = str[0].Split(',');
// creates columns of gridview as per the header name
foreach (string t in temp)
{
dt.Columns.Add(t, typeof(string));
}
// now retrive the record from second line and add it to datatable
for (int i = 1; i < str.Length; i++)
{
string[] t = str[i].Split(',');
dt.Rows.Add(t);
}
DataGridValue.DataSource = dt;
}
void BtnFilterClick(object sender, EventArgs e)
{
// create new DataTable
DataTable dt = ((DataTable)DataGridValue.DataSource);
foreach (DataGridViewRow row in DataGridValue.Rows)
{
// Test if the first column of the current row equals
// the value in the text box
if ((String)row.Cells["Northing"].Value == tbxX1.Text)
{
// we have a match
row.Selected = true;
}
else
{
row.Selected = false;
}
}
Can someone show me the right way how to do this? Thank you very much.
EDITED!!!
Thank you therak for your help. This is working code
dv.RowFilter = String.Format("Northing < '{0}' AND Northing > '{1}'",tbxX2.Text, tbxX1.Text)
what you are looking for is a DataView which you can bind to a DataGridView.DataSource.
DataViews can be filtered/sorted etc. For more info about DataView have a loot at this
In your case it will be something like this:
DataView dv = ((DataTable)DataGridValue.DataSource).DefaultView;
dv.RowFilter = "ColumnName < TB1 AND ColumName > TB2"
Afterwards bind the DataView to your gridView
Try Like this
private void button1_Click(object sender, EventArgs e)
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter =
string.Format("Northing = '{0}'", textBox2.Text);
}
try this haven't tested it but might work for your situation:
void BtnFilterClick(object sender, EventArgs e)
{
// create new DataTable
DataTable filteredDataTable = new DataTable();
filteredDataTable.Columns.Add("csv column");
DataTable dt = ((DataTable)DataGridValue.DataSource);
foreach (DataGridViewRow row in DataGridValue.Rows)
{
// Test if the first column of the current row equals
// the value in the text box
if ((String)row.Cells["Northing"].Value == tbxX1.Text)
{
// we have a match
filteredDataTable.Add(row)
}
}
DataGridValue.DataSource = null;
DataGridValue.DataSource = filteredDataTable;
}

How to populating labels with corresponding row data from selections in a combobox in a c# form

I have a c# form. I have a ComboBox that is the controller. I want to populate labels to display fields from the same row as the selected item in my drop down list.
for example, items is my ComboBox, so if I select an item from my ComboBox, then I want "description" to populate my label, as item ComboBox is selected.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql; //Dir used to connect to sql DB
using System.Data.SqlClient; //Dir used to connect to sql DB
namespace items_Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'syteLine_AppDataSet.item' table. You can move, or remove it, as needed.
this.itemTableAdapter.Fill(this.syteLine_AppDataSet.item);
//creating the connection to database.
SqlConnection con_str = new SqlConnection("Data Source=SL1;Initial Catalog=SyteLine_App;Integrated Security=True");
SqlDataAdapter dta_ad = new SqlDataAdapter("SELECT item, description, lead_time, product_code, p_m_t_code, stocked, matl_type, family_code, low_level, days_supply, order_min, order_mult, plan_code,accept_req, shrink_fact, var_lead, decifld1, decifld2, decifld3, datefld, pass_req, order_max, uf_Active, uf_BoughtOff, uf_Old, uf_ProjectEngineer FROM dbo.item", con_str);
DataTable dta_tbl = new DataTable();
dta_ad.Fill(dta_tbl);
for (int i = 0; i < dta_tbl.Rows.Count; i++)
{
cbxItem.Items.Add(dta_tbl.Rows[i]["item"]);
}
}
public void cbxItem_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbxItem.SelectedIndex == -1)
{
label1.Text = string.Empty;
}
else
{
label1.Text = cbxItem.SelectedItem.ToString();
}
}
}
}
I would only retrieve 1 or 2 columns on page load, JUST to show the dropdown.
I would do a second query in the cbxItem_SelectedIndexChanged method passing in the selected value:
DataTable dt = SomeFunctionThatGetsTheDataForTheSelectedValue(cbxItem.SelectedValue)
lblDescription = dt.Rows[0]["Description"];

Can't bind datatable to Chart Control

I'd like to use a polar chart in my test application. I've a data table with a couple of columns where the column with the name of "X" should provide the x value members, the others should be the y value members. I found a tutorial on MSDN but it doesn't really work because the line
chart1.DataBindTable(dt, "X");
won't compile. Any tip is welcome and thank you.
Here is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace PolarChartTest_01
{
public partial class Form1 : Form
{
public DataTable dt;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt.Rows.Clear();
dt.Columns.Clear();
chart1.Series.Clear();
dt.Columns.Add("X", typeof(int));
dt.Columns.Add("Y", typeof(int));
for (int j = 0; j < 7; j++)
{
DataRow dr = dt.NewRow();
dr["X"] = j * 45;
dr["Y"] = j;
dt.Rows.Add(dr);
}
chart1.DataBindTable(dt, "X");
}
}
}
It won't compile because DataTable doesn't implement IEnumerable interface.
Try:
var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
chart1.DataBindTable(enumerableTable , "X");
This may help you
Write this on page load
chart.DataSource = dataqtableName;
chart.Series["seriesName"].XValueMember = "columNameUwantToBind";
chart.Series["seriesName"].YValueMembers = "columNameUwantToBind";
chart.DataBind();
Another solution might be:
chart1.DataBindTable(dt.DefaultView, "X");
As a bonus, the DataView this returns can be used for sorting and filtering, besides being "databindable".

search for text in a cell of dataGridView and highlight the row?

Im trying to implement a search function for when the user enters text in a textbox (tbPartNum) and then clicks the "Find" button it then searches the cells in dataGridView1 and once its found it, it highlights the entire row yellow. My code is as follows which obviously doesn't work it throws an error which states:
"NullReferenceException was unhandled"
and underneath it:
"Object reference not set to an instance of an object."
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace GBstock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// populate the dataGridView with the Excel File
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", #"C:\Documents and Settings\rghumra\Desktop\Visual Studio\GBstock\GBstock\bin\Debug\FORM TEST.xlsx");
string query = String.Format("select * from [{0}$]", "Sheet1");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
// populates the comboBox (cbSuppList) with all column headers
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
cbSuppList.Items.Add(col.HeaderText);
}
}
private void btnFind_Click(object sender, EventArgs e)
{
// Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER") and highlihgt the row
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))
{
dataGridView1.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
Instructions instructionForm = new Instructions();
instructionForm.Show();
}
private void partToolStripMenuItem_Click(object sender, EventArgs e)
{
NewPart newPartForm = new NewPart();
newPartForm.Show();
}
private void supplierToolStripMenuItem_Click(object sender, EventArgs e)
{
NewSupplier newSuppForm = new NewSupplier();
newSuppForm.Show();
}
}
}
NullReferenceException you're experiencing most likely comes from the fact that your grid contains null cell values, which get scanned in the foreach of your find handler. Try changing the following line:
if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))
To
var cellValue = row.Cells["PART NUMBER"].Value;
if (cellValue != null && cellValue.ToString() == tbPartNum.Text)

Categories

Resources