C# ASP.NET GridView EditTemplate 和查找控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2011207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:38:38  来源:igfitidea点击:

ASP.NET GridView EditTemplate and find control

c#asp.netgridview

提问by Geeth

In the GridView we are using an edit button. Once the edit button is clicked Controls in the edit template will display in the same row with update button. That row has two dropdownlist controls.

在 GridView 中,我们使用了一个编辑按钮。单击编辑按钮后,编辑模板中的控件将与更新按钮显示在同一行中。该行有两个下拉列表控件。

Process flow:

工艺流程:

controls:d1 and d2

控制:d1 和 d2

d1 is using sqldatasource for item display : working fine.

d1 使用 sqldatasource 进行项目显示:工作正常。

d2 is using codebehind code to load the item based on the selected value in the d1 : Not working

d2 正在使用代码隐藏代码根据 d1 中的选定值加载项目:不起作用

How to find the control in the edit template to display item value for d2?

如何在编辑模板中找到控件来显示 d2 的项目值?

采纳答案by Geeth

I got the answer.

我得到了答案。

protected void GridView1_PreRender(object sender, EventArgs e)
 {
  if (this.GridView1.EditIndex != -1)
   {
     Button b = GridView1.Rows[GridView1.EditIndex].FindControl("Button1") as Button;
     if (b != null)
      {
      //do something
      }
   }
 }

回答by Meligy

When you switch to the edit mode, you need to rebind the grid for this to take effect.

当您切换到编辑模式时,您需要重新绑定网格才能使其生效。

So, you can use the 'RowDataBound' event.

因此,您可以使用 'RowDataBound' 事件。

  void MyGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {
    if(e.Row.RowType == DataControlRowType.DataRow
            && e.Row.RowIndex == MyGridView.EditIndex)
    {
      DropDownList d1 = e.Row.FindControl("d1") as DropDownList;
      if(d1 == null) return;
      //Now you have the drop down. Use it as you wish.
    }
  }