e.Row.Cell adding control does not work
I have a code:
protected void gvContacts_RowDatabound(object sender, GridViewRowEventArgs e)
{
Label label = new Label();
label.Text = "tes开发者_开发问答t";
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == 0)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Controls.Add(label); //doesnt work
e.Row.Cells[i].Text = "this works";
}
}
}
where label does not appear to my cells. What's wrong?
You need create a new instance of your label in each loop
for (int i = 0; i < e.Row.Cells.Count; i++)
{
label = new Label();
label.Text = "test";
e.Row.Cells[i].Controls.Add(label);
e.Row.Cells[i].Text = "this works";
}
First things first:
- Make sure the
RowType
is actuallyDataControlRowType.DataRow
- Make sure
e.Row.RowIndex == 0
Set a breakpoint in the code so you can make sure of those values.
After this, it looks like your code should work.
Assuming you've got a header row:
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == 0)
Your row 0 will be of DataControlRowType.HeaderRow
You want != 0, I think
Try to add TableCell before adding control:
TableCell cell = new TableCell();
e.Row.Cells.Add(cell);
e.Row.Cells[i].Controls.Add(label);
精彩评论