无法找到动态生成的文本框的控件

时间:2018-05-03 09:45:48

标签: c# asp.net

我在rowData中生成动态文本框,如下所示,

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
       {  
           try  
           {  
               if (e.Row.RowType == DataControlRowType.DataRow)  
               { 
                   for (int colIndex = 0; colIndex < e.Row.Cells.Count; colIndex++)  
                   {  
                           int rowIndex = colIndex;
                           TextBox txtName = new TextBox();  
                           txtName.Width = 16; 
                           txtName.AutoPostBack = true;  
                           txtName.ID="txtName"
                           e.Row.Cells[colIndex].Controls.Add(txtName); 

                       }  
                   }  
               }  

           }  
           catch (Exception ex)  
           {  
           }  

       } 

按钮点击事件我想找到该文本框的控件,如下所示,

foreach (GridViewRow rows in GridView1.Rows)
 {
      TextBox txtName= (TextBox)rows.FindControl("txtName");

      string test= txtName.Text;

 }

但是上面的代码返回null。 当我尝试在按钮单击事件上找到动态文本框的控件时,它返回null请帮助..

1 个答案:

答案 0 :(得分:2)

您必须设置名称:

txtName.Name = "txtName";    // or txtName.Name = "whatever";