在Grid Row中查找Control

问题描述 投票:4回答:4

我正在使用父子网格和子网格我正在通过javascript进行显示/隐藏。和子网格我用模板列绑定运行时

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并想获得它的价值。

怎么能得到它?

c# asp.net view grid
4个回答
5
投票

您可以使用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表单中以声明方式),则在页面回发后您将无法获得此控件。

罗拉有一篇关于这个主题的文章:Dynamic Web Controls, Postbacks, and View State


3
投票

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

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

如果以上行不起作用,则更改控制指数0。


1
投票

试试这个

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

0
投票

在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);
 }
© www.soinside.com 2019 - 2024. All rights reserved.