I am using ASP.NET with C#. I have GridView
and needed to have two headers. So I used the following code to add another header after data binding.
gridView.DataSource = dataTable;
gridView.DataBind();
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell
{
Text = titleST,
ColumnSpan = 5
};
row.Controls.Add(cell);
row.BackColor = ColorTranslator.FromHtml("#3AC0F2");
row.BorderStyle = BorderStyle.Solid;
row.BorderColor = Color.Black;
row.BorderWidth = Unit.Parse("2");
gridView.HeaderRow.Parent.Controls.AddAt(0, row);
The issue is that when I try to read the data from the gridView
, somehow the first row does not have data.
This is how I read the data:
foreach (GridViewRow row in gridView.Rows)
{
int atmpt = ((DropDownList)row.FindControl("ddlAttemptsT")).SelectedIndex;
Int64 selId = Int64.Parse(((HiddenField)row.FindControl("SelId")).Value);
double wt = int.Parse(row.Cells[2].Text);
double grade = double.Parse(((TextBox)row.FindControl("grade")).Text);
}
I am thinking that I added the new header at index 0 which remove the first row. But In GUI the first row exists. I tried to do AddAt(-1, row)
but that will add it at the bottom of the gridView
.
Any suggestion on how to solve this issue? Please, let me know if I need to clarify my question more. Thank you
CodePudding user response:
Ok, this is a problem of persistence.
When the GV is bound - it also sets up some "things" for view state and how it remembers the layout.
if you AFTER binding, add the header? Then it will display, but is NOT persisted (since it was changed after binding setup). So, with the existing layout - you do in fact wind up over writing the first row.
This means you need to add DURING the binding process.
So, use the RowCreated event. And put your code in that event - say like this:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow Myrow = new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell
{
Text = "My cool title",
ColumnSpan = 5
};
Myrow.Controls.Add(cell);
Myrow.BackColor = ColorTranslator.FromHtml("#3AC0F2");
Myrow.BorderStyle = BorderStyle.Solid;
Myrow.BorderColor = Color.Black;
Myrow.BorderWidth = Unit.Parse("2");
// heading actauly does not exist yet
GridView1.Controls[0].Controls.Add(Myrow);
}
}
And you ONLY bind the grid on post back = false now. Any way, try the above, it should persist, and your first row should now be ok.