我在表单上有一个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;
请帮助。 感谢名单。
答案 0 :(得分:16)
您需要再次对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
}
}
}
答案 1 :(得分:5)
您可以尝试使用此代码 - 基于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