Sai
Sai

Reputation: 103

Listbox won't obtain selected value in ASP.net

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:

enter image description here

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

Answers (2)

bowlturner
bowlturner

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

Nacho
Nacho

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

Related Questions