我有一个 SQL 数据库,我在 C# 中使用 ASP.net。
我有一个下拉框,它选择的项目数据绑定到数据库中的表。基本上,我需要获取所选记录的 ID。
不太确定最好的方法是什么。我只能考虑使用下拉框显示的 SelectedIndex 属性来选择第 n 行。
ID 是唯一标识符类型。请注意,增量 INT 的 ID 不会使用,因为可能会删除记录。
当 DropDown 的 SelectedItem 更改时,您是否指定了将返回哪个字段值?您应该分配字段名称以确保在您选择下拉框中的项目时返回分配的字段值。试试这样的 -
cmbList.DataSource = Your Table or DataSet;
cmbList.DataMember = "ColumnName to be displayed in the DropDownList";
cmbList.DataTextField = "ColumnName to be displayed in the DropDownList";
cmbList.DataValueField = "ColumnName to be returned as SelectedValue in the DropDownList";
cmbList.DataBind();
然后用于DropDownList.SelectedValue
获取您想要的字段值作为 DropDown 的选择结果。希望这可以帮助。
dropdowlist.SelectedValue 将为您提供在 dropdowlist 中选择的项目。dropdowlist.SelectedItem.Text 将为您提供在 dropdowlist 中选择的项目的文本。
protected void dropdowlist_SelectedIndexChanged(object sender, EventArgs e)
{
int ID = dropdowlist.SelectedValue;
---PUT YOUR SELECT CODE HERE----
}
请记住在您的 .aspx 页面中将 dropdowlist Autopostback 属性设置为 true。
<asp:DropDownList ID="dropdowlist" runat="server" AutoPostBack="True" ></asp:DropDownList>