Harry
Harry

Reputation: 2536

Fetching record based on user selection

I've got an SQL Database and I'm using ASP.net in C#.

I've got a drop-down box which has its selection of items databound to a table in the database. Basically, I need to get the ID of the selected record.

Not really sure what the best way to do this would be. I can only think of selecting the nth row by using the SelectedIndex property the drop-down box exposes.

ID is of type uniqueidentifier. Please note that an ID of incremental INT would not be of use because records may be deleted.

Upvotes: 0

Views: 424

Answers (2)

vpv
vpv

Reputation: 938

Did you assign which field value will be returned when the DropDown's SelectedItem is changed? You should assign the field name to make sure the assigned field value returned when you select an item in your DropDown box. Try something like this-

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();

Then use DropDownList.SelectedValue to get your desired field value as the DropDown's selection result. Hope this helps.

Upvotes: 1

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

dropdowlist.SelectedValue will give you the item selected in the dropdowlist. dropdowlist.SelectedItem.Text will give you the text of the item selected in the dropdowlist.

protected void dropdowlist_SelectedIndexChanged(object sender, EventArgs e)
{
    int ID = dropdowlist.SelectedValue;
    ---PUT YOUR SELECT CODE HERE----
}

Do remember to set dropdowlist Autopostback property to true in your .aspx page.

<asp:DropDownList ID="dropdowlist" runat="server" AutoPostBack="True" ></asp:DropDownList>

Upvotes: 1

Related Questions