Reputation: 103
I am trying to get the selected value from a listbox which displays data from my database table. I used DataTable and made it as the data source but the value won't seem to embed from each item in the list.
Here is my line of codes:
Page Load:
DataTable med = new DataTable();
Connection.Open();
SqlDataAdapter viewMed = new SqlDataAdapter("select * from tblListofMedicine", Connection.conn);
viewMed.Fill(med);
lbMedicines.DataSource = med;
lbMedicines.DataValueField = "MedicineName";
lbMedicines.DataTextField = "MedicineName";
lbMedicines.DataBind();
Connection.Close();
btnGetSelected:
string selectedMedicine = lbMedicines.SelectedValue.ToString();
UI properly displaying the data from DT:
The list box shows the text fields properly but I always get nothing every time I try to get its value and I don't know what seems to be the problem here. Any help would be much appreciated.
Upvotes: 0
Views: 89
Reputation: 2016
I am making a few assumptions. It appears the databinding is in the page load, which will run every time you load the page. Do you have it in a
if (!Page.IsPostBack)
{
}
if not you are rebinding your dropdown list box every time the page posts back, so you won't have a selected value.
Upvotes: 0
Reputation: 1013
Use Page.IsPostBack
in your page_load
if (!Page.IsPostBack)
{
//your code
}
The postback clear your selection.
I hope help you.
Upvotes: 2