C# 如何在编辑项模板中找到控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14584175/
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
how to find control in edit item template?
提问by Mogli
i have a gridview on the form and have some template field, one of them is:
我在表单上有一个 gridview 并有一些模板字段,其中之一是:
<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="DdlCountry" runat="server" DataTextField="Country" DataValueField="Sno">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
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:
现在在 RowEditing 事件中,我需要获取国家下拉列表的选定值,然后将该值设置为 Ddlcountry.selectedvalue=value;这样当编辑项模板的下拉列表出现时,它将显示所选值而不是下拉列表的 0 索引。但我无法获得下拉列表的值。我已经试过了:
int index = e.NewEditIndex;
DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;
need help please. thanx.
需要帮助请。谢谢。
采纳答案by Tim Schmelter
You need to databind the GridView
again to be able to access the control in the EditItemTemplate
. So try this:
您需要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;
But instead i would use RowDataBound
for this, otherwise you're duplicating code:
但是我会为此使用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
}
}
}
回答by Aghilas Yakoub
You can try wit this code - based on EditIndex property
你可以试试这个代码 - 基于 EditIndex property
var DdlCountry = GridView1.Rows[GridView1.EditIndex].FindControl("DdlCountry") as DropDownList;
Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.gridview.editindex.aspx
链接:http: //msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.gridview.editindex.aspx