The
GridView
control will generate data based on it's
datasource
, so technically you could manipulate the
datasource
and add whatever you like in there before populating the grid. For example, if you are using
DataTable
, you could construct the
Rows
and
Columns
dynamically and populate them with data:
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));value
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
Gridview1.DataSource = dt;
Gridview1.DataBind();
If you have an existing
DataTable
and would like to add a new
Column
for your row number then you have to iterate to each
DataRow
and append the row number:
DataTable source = ???;
DataColumn newCol = new DataColumn("RowNumber", typeof(string));
tbl.Columns.Add(newCol);
int i = 0;
foreach (DataRow row in source.Rows) {
i++;
row["RowNumber"] = i.ToString();
}
With that, you can then set the
RowNumber
column as
DataField
value like this:
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />