Gridview EditItemTemplate DropDownList获取SelectedValue

在我的Gridview中,我有以下模板字段:

     <asp:DropDownList ID="ddlDeptCode" runat="server" SelectedValue='' DataSource='' DataTextField="DeptCode" DataValueField="DeptCode" />   

当我在一行上单击“编辑”时,它会很好地工作,它会使用所有值填充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 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; } } } 

在绑定gridview时,我正在使用一些黑客来获取表标题的第二个标题:

 GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal); TableCell th = new TableHeaderCell(); th.HorizontalAlign = HorizontalAlign.Center; th.ColumnSpan = UserGV.Columns.Count; th.BackColor = Color.SteelBlue; th.ForeColor = Color.White; th.Font.Bold = true; th.Text = "Manage Users"; row.Cells.Add(th); InnerTable.Rows.AddAt(0, row); 

我不完全理解这是如何干扰获取DropDownList控件的SelectedValue但是只要我评论它开始工作。

对于那些感兴趣的人,我使用不同的方法得到了第二个标题:

在.aspx文件中,我将其添加到Gridview:

 OnRowCreated="CreateRow" 

在后面的代码中我添加了以下方法:

 protected void CreateRow(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { GridView gridView = (GridView)sender; GridViewRow row = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Normal); TableCell th = new TableHeaderCell(); th.HorizontalAlign = HorizontalAlign.Center; th.ColumnSpan = UserGV.Columns.Count; th.ForeColor = Color.White; th.BackColor = Color.SteelBlue; th.Font.Bold = true; th.Text = "Manage Users"; row.Cells.Add(th); gridView.Controls[0].Controls.AddAt(0, row); } } 

现在一切正常。