How to display serial number in datagridview?

久未见 提交于 2020-01-16 00:39:39

问题


i am using windows application with C#. I want to display Serial number in datagridview.


回答1:


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.




回答2:


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

link




回答3:


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);
        }
    }



回答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();
    }


来源:https://stackoverflow.com/questions/25697917/how-to-display-serial-number-in-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!