在Grid Row中查找Control

即时通讯使用父子网格和子网格我做显示/隐藏扔java脚本。 和子网格我用Templatecolumns绑定运行时间

GridView NewDg = new GridView(); NewDg.ID = "dgdStoreWiseMenuStock"; TemplateField TOTAL = new TemplateField(); TOTAL.HeaderTemplate = new BusinessLogic.GridViewTemplateTextBox(ListItemType.Header, "TOTAL",e.Row.RowIndex ); TOTAL.HeaderStyle.Width = Unit.Percentage(5.00); TOTAL.ItemTemplate = new BusinessLogic.GridViewTemplateTextBox(ListItemType.Item, "TOTAL", e.Row.RowIndex); NewDg.Columns.Add(TOTAL); NewDg.DataSource = ds; NewDg.DataBind(); NewDg.Columns[1].Visible = false; NewDg.Columns[2].Visible = false; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); NewDg.RenderControl(htw); 

现在我在Grid中有一个名为“TOTAL”的TextBox我想找到这个TextBox并想获得它的价值。

怎么能得到它?

您可以使用Controls属性或FindControl(string id)方法在GridView的相应单元格内获取TextBox控件:

 TextBox txtTotal = gv.Rows[index].cells[0].Controls[0] as TextBox; 

要么

 TextBox txtTotal = gv.Rows[index].cells[0].Controls[0].FindControl("TOTAL") as TextBox; 

其中index对于第一行可以是0,或者对于for循环可以是迭代器。

或者,您可以在GridView的行上使用foreach循环:

 foreach(GridViewRow row in gv.Rows) { TextBox txtTotal = row.cells[0].Controls[0].FindControl("TOTAL") as TextBox; string value = txtTotal.Text; // Do something with the textBox's value } 

此外,您必须记住,如果您正在动态创建GridView(而不是在Web表单中以声明方式),则在页面回发后您将无法获得此控件。

Rolla有一篇关于这个主题的文章: 动态Web控件,回发和视图状态

如您所知,您可能会获得第一行和第一个单元格的TextBox值:

 ((TextBox) dgdStoreWiseMenuStock.Rows[0].Cells[0].Controls[1]).Text; 

或者如果上面的行不起作用,则改变控制指数0。

试试这个

  TextBox txtTotal = (TextBox)gv.Rows[index].cells[0].FindControl("TOTAL"); string value = txtTotal.Text; 

在gridview中查找控件的最简单方法是使用foreach循环来查找行

  foreach (GridViewRow row in Gridname.Rows) { TextBox txttotal = (TextBox)row.FindControl("textboxid_inside_grid"); string var = txttotal.Text; Response.Write("Textbox value = " + var); }