i am using windows application with C#. I want to display Serial number in datagridview.
4 Answers
You need to bind DataBindingComplete event of datagridview.
private void gridStateZone_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
LoadSerial(gridStateZone);
}
private void LoadSerial(DataGridView grid)
{
foreach (DataGridViewRow row in grid.Rows)
{
grid.Rows[row.Index].HeaderCell.Value = string.Format("{0} ", row.Index + 1).ToString();
row.Height = 25;
}
}
It's work for me.
In WinForms Applications, to display the row number in the row header, we could use the RowPostPaint event of DataGridView control.
Usage: Suppose grid is named as dgvUserDetails
Delegate
this.dgvUserDetails.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgvUserDetails_RowPostPaint);
Code
private void dgvUserDetails_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
using (SolidBrush b = new SolidBrush(dgvUserDetails.RowHeadersDefaultCellStyle.ForeColor))
{
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);
}
}
Don’t try to manipulate the Code part much because the X and Y are calculated co-ordinates in the row header area or you can customizse test it yourself to see the various results.
Result
private void grid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e )
{
using (SolidBrush b = new SolidBrush(((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor))
{
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);
}
}
private void DgvSupplierInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (dgvSupplierInfo == null)
return;
int sno = 1;
string columnName = "columnName";
string headerText = "headerText";
if (dgvSupplierInfo.Columns.Contains(columnName))
dgvSupplierInfo.Columns.Remove(columnName);
{
dgvSupplierInfo.Columns.Add(columnName, headerText);
}
dgvSupplierInfo.Columns[columnName].DisplayIndex = 0;
foreach (DataGridViewRow row in dgvSupplierInfo.Rows)
row.Cells[columnName].Value = sno++;
dgvSupplierInfo.AutoResizeColumns();
}