Windows Develop Bookmark and Share   
 index > Windows Forms General > Selected Item in a List Box
 

Selected Item in a List Box

Hi there,

I've populated a list box on my form load as follows:

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

ListBoxBind();

}

}

protected void ListBoxBind()

{

SqlConnection SqlCon = new SqlConnection("Data Source=mssql.stormwebhost.com;Initial Catalog=database;User ID=User;Password=Password;");

SqlCommand SqlCmd = new SqlCommand("SELECT * FROM tblCatDetails WHERE ListId ='" + Session["ListIdLog"] + "'", SqlCon);

SqlCon.Open();

lb1.DataSource = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);

lb1.DataTextField = "CatDescription";

lb1.DataValueField = "ListId";

lb1.DataBind();

}

However when i try to get the selected item value i keep getting returnedthe value of the first list box item. I have tried setting the autopostback to true but to no avail.

Any help would be greatly appreciated,

Thanks,

Aidan.

Aidan Mullane  Tuesday, March 13, 2007 11:59 AM

Postbacks are how information gets sent back to the page. You can't avoid them. It seems like someone is resetting the data source for your list box. Your initial code for binding the control is correct. It will only bind the first time the page is loaded. Search for any occurrences of anyone setting the DataSource or DataSourceId properties in your code. You should also check your ASPX page. If you were to accidentally set the DataSource property in the ASPX page then you would lose your data on postback. Note that DataSourceId can, and is, set in the ASPX page and, provided you want to use the data source, will work correctly. However you can't set both DataSource and DataSourceId at the same time. If you can't figure it out then try hooking up an event to the list box when the data binding changes. This will fire whenever the binding occurs and will let you confirm that it only happens when you wanted it to. Finally be sure that you didn't disable viewstate for the control or page as this might cause some problems.

Michael Taylor - 3/13/07
http://p3net.mvps.org

TaylorMichaelL  Tuesday, March 13, 2007 3:39 PM

That would be the expected behavior. In your command you are requesting all rows where ListId is a specific session value. Therefore all returned rows will have the same value for ListId. You are then storing that value in the control. Later when you retrieve the value back from SelectedValue it will always be equal to Session["ListIdLog"]. Did you try checking to see if SelectedText returned the correct description for the item you selected?

Michael Taylor - 3/13/07
http://p3net.mvps.org

TaylorMichaelL  Tuesday, March 13, 2007 12:25 PM

This code i have behind my list box's selected index change is as follows:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)

{

int category;

category = lb1.SelectedItem;

Session["Category"] = category;

}

No matter which item i select from my list box it alwaysreturns the first value from my list box as the selected item.

Aidan Mullane  Tuesday, March 13, 2007 2:27 PM
Might not be an issue but I noticed that your listbox name is lb1 but the function name is ListBox1, did you check to make sure your lb1 SelectedIndexChanged event is calling the right function? I doupt this is it but figured I would check, sometimes the easy stuff is the hardest to see.

theTroll
theTroll527  Tuesday, March 13, 2007 2:37 PM

Given the way you set up the list box SelectedItem will be a ListItem containing the selected item. Note however that this event is raised whenever the property changes so if you were to set SelectedIndex before binding the control then it wouldn't work properly.

I'd recommend that you switch to a data source rather than hand writing the databinding code. It cleans things up a lot and might help resolve your problem. I noticed that in your code you are not cleaning up the connection or data reader objects. For a website you will quickly deadlock the site because of this. Using a data source eliminates this problem. In your case you'd drop a SqlDataSource onto your form and then configure it appropriately. You'd then use the smart tag on the list box to associate it with the data source and set the fields to display for the text and value. You could then remove all your code that you wrote other than the event handler.

Michael Taylor - 3/13/07
http://p3net.mvps.org

TaylorMichaelL  Tuesday, March 13, 2007 2:48 PM

No unfortunately thats not it. Its calling the right function alright. I can see that from when i debug it.

I think the problem has to do with the postback to the server. How do i stop the postback to the server on my Listbox. It appears that other functions on my page are causing the value of my lisy box to reset. I thought the (!Page.IsPostBack) on my fprm load would stop this?

Thanks,

Aidan.

Aidan Mullane  Tuesday, March 13, 2007 2:58 PM

Hi Michael,

I had my list box populating from a sqldatasource but i had the same issue. That is why i am now populating it through code. I thought that if i could popuate it through code that i would be able to see exactly what was going wrong. However the problem exists. I'm pretty sure it has something to do with the postback to the server. I've noticed that if i use anycontrol on my page that the selected item gets reset im my list box.

Is there any way i can stop this?

Thanks,

Aidan.

Aidan Mullane  Tuesday, March 13, 2007 3:30 PM

Postbacks are how information gets sent back to the page. You can't avoid them. It seems like someone is resetting the data source for your list box. Your initial code for binding the control is correct. It will only bind the first time the page is loaded. Search for any occurrences of anyone setting the DataSource or DataSourceId properties in your code. You should also check your ASPX page. If you were to accidentally set the DataSource property in the ASPX page then you would lose your data on postback. Note that DataSourceId can, and is, set in the ASPX page and, provided you want to use the data source, will work correctly. However you can't set both DataSource and DataSourceId at the same time. If you can't figure it out then try hooking up an event to the list box when the data binding changes. This will fire whenever the binding occurs and will let you confirm that it only happens when you wanted it to. Finally be sure that you didn't disable viewstate for the control or page as this might cause some problems.

Michael Taylor - 3/13/07
http://p3net.mvps.org

TaylorMichaelL  Tuesday, March 13, 2007 3:39 PM

You can use google to search for other answers

Custom Search

More Threads

• Training cards
• How to make a usercontrol to act as an container?
• C#.NET APP: How to bind a vscrollbar component to a control?
• Can't load resources from satellite assembly
• Kiosk applicaiton using .net 2.0
• Tree to Tree animation
• Get X and Y coordinates
• Testing scalar query for NULL
• Questions about PropertyGrid and ListView
• OS Language