【问题标题】:Find Control inside Grid Row在网格行中查找控件
【发布时间】:2010-12-30 06:22:46
【问题描述】:

我正在使用父子网格,在子网格上我正在执行显示/隐藏抛出 java 脚本。和子网格我将运行时间与模板列绑定,如

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”的文本框,我想查找此文本框并获取它的值。

如何获得?

【问题讨论】:

    标签: c# asp.net view grid


    【解决方案1】:

    您可以使用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;
    

    第一行的索引可以是 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 表单中以声明方式),您将无法在页面回发后获得此控件。

    有一篇很棒的 4 Guys from Rolla 关于这个主题的文章:Dynamic Web Controls, Postbacks, and View State

    【讨论】:

      【解决方案2】:

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

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

      如果上面的行不起作用,或者将控制的索引设置为 0。

      【讨论】:

        【解决方案3】:

        试试这个

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

        【讨论】:

          【解决方案4】:

          在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);
           }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-10-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-23
            • 1970-01-01
            • 2013-01-31
            相关资源
            最近更新 更多