Pages

Monday, October 1, 2012

DataSet,DataBinding,BindingSource

DataGridView Auto Number After Binding The Data

 Auto generate row number in DataGridView in windows application. Its simple below code shows how to do that.
Just you need to pass your datagridview in below function and it will generate auto number to Header cell.
NOTE: First you have to bind the datagridview with data then call the below function.
Using C# code

//Auto Generate number

public void AutoNumberRowsForGridView(DataGridView dataGridView)

{

    if (dataGridView != null)

   {

    for (int count = 0; (count <= (dataGridView.Rows.Count - 2)); count++)

     {

       dataGridView.Rows[count].HeaderCell.Value = string.Format((count + 1).ToString(), "0");

      }
   }
}

And Display Numbers In DataGridView First Cell:


private void dataGridViewAutoNumber()
        {
            for (int row = 0; row < dataGridView1.RowCount - 1; row++)
            {
                dataGridView1.Rows[row].Cells[0].Value = row + 1;
            }
        }