I have binded a datagridview with access database table. I want to add a new custom column to DataGridView when the program loads. This column contains the auto incremented number "Serial Number" for the rows in the DataTable. The code is below,
using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
{
conn.Open();
command = new OleDbCommand("SELECT s.RollNo, s.SName, s.FName, s.DOB, c.Class, s.[Section],s.Picture from students as s left outer join classes as c " +
"on c.ClassID = s.ClassID", conn);
dTable = new DataTable();
dTable.Load(command.ExecuteReader());
dgvDisplay.Columns.Add("SrNo", "Sr No"); // Adding "Serial No" Column to DataGridView
dgvDisplay.DataSource = dTable;
dgvDisplay.Sort(dgvDisplay.Columns["RollNo"], ListSortDirection.Ascending);
// Change Column Headings
dgvDisplay.Columns["RollNo"].HeaderText = "Roll No";
dgvDisplay.Columns["SName"].HeaderText = "Student Name";
dgvDisplay.Columns["FName"].HeaderText = "Father Name";
dgvDisplay.Columns["DOB"].HeaderText = "Date Of Birth";
// Serial Number code
int srNo = 1;
foreach(DataGridViewRow row in dgvDisplay.Rows)
{
row.Cells["SrNo"].Value = srNo;
srNo++;
}
}
But When I run the program the Serial number Column is empty. This column have to show numbers like 1,2,3.. for rows in gridview.
Now I changed the code for new column addition. I try this code below
dTable.Columns.Add(new DataColumn("SrNo", typeof(Int32))); // Adding "Serial No" Column to DataTable
dgvDisplay.DataSource = dTable;
dgvDisplay.Sort(dgvDisplay.Columns["RollNo"], ListSortDirection.Ascending);
// Serial Number code
int srNo = 1;
foreach (DataRow row in dTable.Rows)
{
row["SrNo"] = srNo;
srNo++;
}
This generate the Serial No but according to the order of the DataTable as the Record Rows are inserted to it.