在 GridView 中编辑行时,我需要一个 DropDownList,其可用值列表取决于该行中的其他列(现在我们只说记录的“类型”);也就是说,根据正在编辑的行,将列出不同的选项。
我通过向 GridView 添加一个本来不需要的 DataKeyName 来让它工作,但这在其他地方引起了我的悲伤,而且无论如何它感觉太迂回了,所以我正在寻找更好的方法。这是我目前正在做的事情:
在 .aspx 文件中:
<asp:GridView ID="gvDct" ... DataKeyNames="dctId,dctType" ... >
...
<asp:TemplateField>
...
<EditItemTemplate>
<asp:DropDownList ID="ddlDctParent" runat="server"
DataSourceId="sdsDctParent"
DataValueField="dctId" DataTextField="dctFullPath"
SelectedValue='<%# Bind("dctParentId") %>'
... >
</asp:DropDownList>
<asp:SqlDataSource ID="sdsDctParent" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="sdsDctParent_Selecting"
SelectCommand="SELECT dctId, dctFullPath FROM lkpDocCatAndType
WHERE dctType=@dctType">
<SelectParameters>
<asp:Parameter Name="dctType" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
...
</asp:GridView>
我希望 SelectParameter 成为 ControlID="gvDct" 且 PropertyName="SelectedDataKey.Values[dctType]" 的 ControlParameter,但由于未知原因不起作用(参数值为空),因此我将这一点添加到.vb 代码隐藏文件,用于填充 DropDownList 数据源的行特定参数:
Protected Sub sdsDctParent_Selecting(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
e.Command.Parameters(0).Value = gvDct.DataKeys(gvDct.EditIndex).Item(1)
End Sub
因此,当我开始在 GridView 中编辑一行时,DropDownList 被绑定,这会导致 SqlDataSource SelectCommand 执行,从而触发 OnSelecting 代码,我在其中提供正在编辑的行 (EditIndex) 中的参数值,以便我获得DropDownList 中适当的值群体。
有“更好”的方法吗?对我来说最重要的方面是避免添加 DataKeyName,因为这会导致我用于从 GridView 中删除行的存储过程出现参数过多的问题。
您应该使用 Gridview
RowDataBound
,您可以在其中获取 valueID,稍后您可以填充您的 Dropdownlist
还添加一个 label/hidden
字段,您想要填充 DropdownList 的值你可以尝试这样的事情
protected void gvDct_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblValue = (Label)e.Row.FindControl("YourLableID")
DropDownList ddList= (DropDownList)e.Row.FindControl("ddlDctParent");
//bind dropdownlist
DataTable dt = con.GetData("Select Query where YourColumn='"+lblValue.text+"'");
ddList.DataSource = dt;
ddList.DataTextField = "dctFullPath";
ddList.DataValueField = "dctId";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
ddList.SelectedValue = dr["dctId"].ToString();
}
}
}