如何在编辑项模板中找到控件? [英] how to find control in edit item template?

查看:26
本文介绍了如何在编辑项模板中找到控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a gridview on the form and have some template field, one of them is:

<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 索引.但我无法获得下拉列表的值.我已经试过了:

now on the RowEditing event i need to get the selected value of dropdownlist of country and then i will set that value as Ddlcountry.selectedvalue=value; so that when dropdownlist of edit item template appears it will show the selected value not the 0 index of dropdownlist. but i am unable to get the value of dropdown list. i have tried this already:

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

需要帮助.谢谢.

推荐答案

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

You need to databind the GridView again to be able to access the control in the EditItemTemplate. So try this:

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 ,否则您将重复代码:

But instead i would use RowDataBound for this, otherwise you're duplicating code:

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
        }
   }
}

这篇关于如何在编辑项模板中找到控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆