在我的 Gridview 中,我有以下模板字段:
<asp:TemplateField HeaderText="Dept Code" SortExpression="DeptCode">
<ItemTemplate>
<%# Eval("DeptCode") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlDeptCode" runat="server"
SelectedValue='<%# Eval("DeptCode") %>'
DataSource='<%# GetAllDepartments() %>'
DataTextField="DeptCode"
DataValueField="DeptCode" />
</EditItemTemplate>
</asp:TemplateField>
当我在一行上单击编辑时,这非常有用,它会使用所有值填充 DropDownList 并为该行选择正确的值。
但是,当我尝试更新该行时:OnRowUpdating="UpdateRow"
protected void UpdateRow(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = UserGV.Rows[e.RowIndex];
DropDownList ddl = row.FindControl("ddlDeptCode") as DropDownList;
string deptCode = ddl.SelectedValue;
}
它找到 DropDownList 控件,但 SelectedValue 始终为空字符串。
我需要访问所选值以保存到数据库。
关于如何在后面的代码中获取 Gridview 中 DropDownList 的 SelectedValue 的任何想法?
编辑:
您还可以从后面的代码中填充 DropDownList 和 SelectedValue:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
var deptMgr = new DepartmentMgr();
List<Department> departments = deptMgr.GetAllDepartments();
DropDownList ddList = (DropDownList)e.Row.FindControl("ddlDeptCode");
ddList.DataSource = departments;
ddList.DataTextField = "DeptCode";
ddList.DataValueField = "DeptCode";
ddList.DataBind();
string userDeptCode = DataBinder.Eval(e.Row.DataItem, "DeptCode").ToString();
ddList.SelectedItem.Text = userDeptCode;
ddList.SelectedValue = userDeptCode;
}
}
}