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?
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.
I use a ViewState to do this, as follows:
SeqNo
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With