在网格行内查找控件

use*_*146 4 c# asp.net grid view

我使用父子网格,并在子网格上即时显示/隐藏抛出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);
Run Code Online (Sandbox Code Playgroud)

现在,我在Grid中有一个名为“ TOTAL”的TextBox,我想查找此TextBox并想获取其值。

如何获得它?

ale*_*phi 5

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

TextBox txtTotal = gv.Rows[index].cells[0].Controls[0] as TextBox;
Run Code Online (Sandbox Code Playgroud)

要么

TextBox txtTotal = gv.Rows[index].cells[0].Controls[0].FindControl("TOTAL") as TextBox;
Run Code Online (Sandbox Code Playgroud)

其中第一行的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
}
Run Code Online (Sandbox Code Playgroud)

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

Rolla上有一篇很棒的4个人关于该主题的文章:动态Web控件,回发和视图状态