C# 如何在编辑项模板中找到控件?
我在表单上有一个gridview和一些模板字段,其中之一是:C# 如何在编辑项模板中找到控件?,c#,asp.net,gridview,C#,Asp.net,Gridview,我在表单上有一个gridview和一些模板字段,其中之一是: <asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left"> <EditItemTemplate> <asp:DropDownList ID="DdlCountry" runat="server" DataTextField="Country" DataValueField="Sno">
<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="DdlCountry" runat="server" DataTextField="Country" DataValueField="Sno">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
我需要帮助。
thanx.您需要再次对
网格视图进行数据绑定,以便能够访问编辑项模板中的控件。所以试试这个:
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
}
}
}
您可以尝试使用此代码-基于EditIndex属性
var DdlCountry = GridView1.Rows[GridView1.EditIndex].FindControl("DdlCountry") as DropDownList;
链接:找不到DDLCORITY控件,它在DDLCORITY变量中显示null?是的,这也不起作用。它似乎是在创建ddlcountry的一个新实例,而不是在编辑模式下的引用。在GridView事件句柄方法之外(例如,在ModelBinding方法中),该方法尤其有效。最后得到了dropdown的参考:)但我采用了不同的方式将所选值分配给dropdown。我使用gridview的datakey属性。thnx很多Tim先生:)有没有办法,我不必再次点击de DB,而是在编辑启动时绑定de dropdownlist第一个示例对我不起作用,但RowDataBound确实起作用。非常感谢。
var DdlCountry = GridView1.Rows[GridView1.EditIndex].FindControl("DdlCountry") as DropDownList;