我的表单上有一个 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;
请需要帮助。
谢谢。
您需要进行数据绑定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
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)