Mayank Jani

Mayank Jani

  • 1.6k
  • 477
  • 57.4k

How to add serial number in databound gridview?

Mar 22 2018 1:27 PM
Hi members,
 
Greetings of the day.
 
I am working on a C# winapp form. it is about fetching details of employees from different cities. I select city from a dropdownlist and the system fetches all the employees from the city and shows the data into a datagridview.
the first column is Sr No (Serial number, obviously) and when the data shows in the gridview, it is like 3, 5, 12, 18. the serial number given in the db.
can I fetch the data from the db but the serial number should be 1,2,3,4...n regardless what actual serial in the db?
 
my code is....
 
private void btnSearch_Click(object sender, EventArgs e)
{
OleDbDataAdapter SearchEmp = new OleDbDataAdapter("Select CrysName, CrysCity, CrysDesig, CrysSalary From CrysPort Where CrysCity='" + cmbCity.SelectedValue.ToString() + "'", MyConn);

DataSet dsSearchEmp = new DataSet();
SearchEmp.Fill(dsSearchEmp);
 
if (dsSearchEmp.Tables[0].Rows.Count > 0)
{
dgvPrintSettings.DataSource = dsSearchEmp.Tables[0];

dgvPrintSettings.Columns[0].Width = 45;
dgvPrintSettings.Columns[0].HeaderText = "Sr No";
dgvPrintSettings.Columns[1].Width = 125;
dgvPrintSettings.Columns[1].HeaderText = "Employee Name";
dgvPrintSettings.Columns[2].Width = 85;
dgvPrintSettings.Columns[2].HeaderText = "Emp. City";
dgvPrintSettings.Columns[3].Width = 75;
dgvPrintSettings.Columns[3].HeaderText = "Designation";
dgvPrintSettings.Columns[4].Width = 55;
dgvPrintSettings.Columns[4].HeaderText = "Salary";
}

}

i have searched some point on the net but there is something that i do not understand how to apply.
 
int i = 1;

foreach (DataGridViewRow R1 in dgvPrintSettings.Rows)
{
R1.Cells["Sr No"].Value = i; i++;
}
 
if it is correct, where should i put this code?
 
Thank You.
 
Mayank Jani

Answers (3)