问题
<asp:GridView ID="GridView1" runat="server" >
<asp:TemplateField HeaderText="Token" SortExpression="Token" HeaderStyle-Width="100px">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
update:
after i view the source code of the page thsi is what i see the id of a textbox that i have created dynamic.
ctl00_ContentPlaceHolder1_tabControl_tabUsers_MyControl1_gv_ctl02__token0_3
OnRowUpdating:
TextBox _token = gvOrg.Rows[e.RowIndex].Cells[7].FindControl("_token " + e.RowIndex + "_" + rowId) as TextBox;
Update end:
i am adding few textbox dynamic in OnRowDataBound and whe i try getting the value then i am getting null
here is my code:
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
for (int rowId = 0; rowId < 5; rowId++)
{
TextBox _token = gvOrg.Rows[e.RowIndex].Cells[7].FindControl("_token" + rowId) as TextBox;
}
}
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit))
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int rowId = 0; rowId < 5; rowId++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "_token" + rowId;
txtBox.Text = "token" + rowId;
e.Row.Cells[7].Controls.Add(txtBox);
}
}
回答1:
You are creating textbox for each row - 5 of them... and in each row, each of those textboxes has the same id as the other rows. You need to at the row's index, for example, to the name of the textboxes when you create them. You can't have a control on the page with the same id, or else it can't be found correctly.
Here is one way to do that.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit))
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int rowId = 0; rowId < 5; rowId++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "_token" + e.Row.RowIndex + "_" + rowId;
txtBox.Text = "token" + rowId;
e.Row.Cells[7].Controls.Add(txtBox);
}
}
I can't test that this is the complete solution, but it is a place to start.
回答2:
here is how i able to fix the problem: instead of creating in rowdatabound i am creating on RowCreated, hope this will help others.
protected void gridviwe1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int rowId = 0; rowId < 5; rowId++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "_registration" + e.Row.RowIndex + "_" + rowId;
txtBox.Text = "_registration" + e.Row.RowIndex + "_" + rowId;
e.Row.Cells[7].Controls.Add(txtBox);
}
}
}
来源:https://stackoverflow.com/questions/4751565/how-can-i-read-a-dynamically-created-textbox-gridview-onrowupdating