Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating row numbers automatically in the header of dataGridView

I'm new to using the C#/.NET programming Language and I have created a DataGridView for adding, editing and deleting records.

I am using Visual Studio 2010 for coding. I have put in an unbound column for row number and have this method for displaying the auto generated row numbers.

private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.Cells["rownumber"].Value = row.Index + 1;                
            }
            e.Row.Cells["min_bracket"].Value = 0;
            e.Row.Cells["max_bracket"].Value = 0;
            e.Row.Cells["tax_percent"].Value = 0;
            e.Row.Cells["add_amount"].Value = 0;
        }

This does work when inserting values into the datagrid but does not show any numbers in the rownumber column when retrieving values.

How do I get to have auto generated numbers in the header instead of having to create an unbound column like I have that works when inserting rows and retrieving records?

like image 574
Kinyanjui Kamau Avatar asked Oct 20 '25 14:10

Kinyanjui Kamau


2 Answers

To display text in the row header you can use the Row.HeaderCell.Value as shown below:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    DataGridView gridView = sender as DataGridView;
    if (null != gridView)
    {
        foreach (DataGridViewRow r in gridView.Rows)
        {
            gridView.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
        }
    }
}

This only displays the row number of the new row when the user begins typing in it. Not sure if there is a simple way of always showing the row number on the new row.

like image 171
David Hall Avatar answered Oct 23 '25 08:10

David Hall


I use a ViewState to do this, as follows:

  1. Add a template column for the row count
  2. Bind its content to a property like SeqNo
  3. Create the property SeqNo in your code-behind, returning the current row count (try the below code)
int _seq = 0;

public int SeqNo {
  get {
    if (ViewState["seq"] == null) {
        ViewState["seq"] = 1;
    } else {
        ViewState["seq"] = int.Parse(ViewState["seq"].ToString()) + 1; 
    }
    _seq = int.Parse(ViewState["seq"].ToString());
    return _seq;
  }
} 

And for the aspx side ,add the template Column to your interest GridView as the following

                 <asp:TemplateField HeaderText="" >
                    <ItemTemplate>
                        <%=SeqNo%>
                    </ItemTemplate>
                </asp:TemplateField>
like image 28
saeed Avatar answered Oct 23 '25 08:10

saeed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!