2012-05-28 114 views
0

我有一個SQL數據庫,我在C#中使用ASP.net。基於用戶選擇獲取記錄

我有一個下拉框,其選擇項數據綁定到數據庫中的表。基本上,我需要獲取所選記錄的ID。

不太確定要做到這一點的最佳方法是什麼。我只能想到通過使用下拉框公開的SelectedIndex屬性來選擇第n行。

ID是uniqueidentifier類型。請注意,由於記錄可能被刪除,所以增量INT的ID不會被使用。

回答

1

您是否指定在DropDown的SelectedItem被更改時將返回哪個字段值?您應該指定字段名稱,以確保在您的DropDown框中選擇一個項目時返回指定的字段值。嘗試這樣的事情 -

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的選擇結果。希望這可以幫助。

+0

輝煌。我已將數據源更改爲包含ID字段和我的標記以包含DataValueField。 – morph

1

dropdowlist.SelectedValue會給你在下拉列表中選擇的項目。 dropdowlist.SelectedItem.Text將爲您提供在下拉列表中選擇的項目的文本。

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> 
+0

@Harreh只記得在綁定數據時,將DropDownList Item的選定值設置爲數據的唯一行ID。 –

+0

SelectedValue屬性僅返回在下拉列表中使用的文本。這對我來說並不奇怪,因爲它連接到數據源的方式。 – morph