【问题标题】:how to find control in edit item template?如何在编辑项模板中找到控件?
【发布时间】:2013-01-13 02:21:40
【问题描述】:

我在表单上有一个 gridview 并有一些模板字段,其中之一是:

<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
    <EditItemTemplate>
        <asp:DropDownList ID="DdlCountry" runat="server" DataTextField="Country" DataValueField="Sno">
        </asp:DropDownList>
    </EditItemTemplate>
    </asp:TemplateField>

现在在 RowEditing 事件中,我需要获取国家下拉列表的选定值,然后我将该值设置为 Ddlcountry.selectedvalue=value;这样当编辑项模板的下拉列表出现时,它将显示所选值而不是下拉列表的 0 索引。但我无法获得下拉列表的值。 我已经试过了:

int index = e.NewEditIndex;
DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;

需要帮助。 谢谢。

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    您需要再次对GridView 进行数据绑定,才能访问EditItemTemplate 中的控件。所以试试这个:

    int index = e.NewEditIndex;
    DataBindGridView();  // this is a method which assigns the DataSource and calls GridView1.DataBind()
    DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;
    

    但我会为此使用RowDataBound,否则你就是在复制代码:

    protected void gridView1_RowDataBound(object sender, GridViewEditEventArgs e)
    {
     if (e.Row.RowType == DataControlRowType.DataRow)
      {
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
              DropDownList DdlCountry = (DropDownList)e.Row.FindControl("DdlCountry");
              // bind DropDown manually
              DdlCountry.DataSource = GetCountryDataSource();
              DdlCountry.DataTextField = "country_name";
              DdlCountry.DataValueField = "country_id";
              DdlCountry.DataBind();
    
              DataRowView dr = e.Row.DataItem as DataRowView;
              Ddlcountry.SelectedValue = value; // you can use e.Row.DataItem to get the value
            }
       }
    }
    

    【讨论】:

    • 终于得到了下拉列表的引用 :) 但我采用不同的方式将所选值分配给下拉列表。我经常使用 gridview.thnx 的 datakey 属性 Tim 先生 :)
    • 有什么办法,我不必再次点击 de DB,而是在编辑触发时绑定 de 下拉列表
    • 第一个例子对我不起作用,但 RowDataBound 起作用了。谢谢
    【解决方案2】:

    您可以尝试使用此代码 - 基于 EditIndex property

    var DdlCountry  = GridView1.Rows[GridView1.EditIndex].FindControl("DdlCountry") as DropDownList;
    

    链接:http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.gridview.editindex.aspx

    【讨论】:

    • 无法找到 ddlcountry 控件,它在 DdlCountry 变量中显示为空?
    • 是的,这也不起作用。它似乎是在创建一个新的 ddlcountry 实例,而不是对处于编辑模式的实例的引用
    • 这在 GridView 事件句柄方法之外特别有效(例如在 ModelBinding 方法中)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多