Click here to Skip to main content
15,943,008 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hi frnds,

I got a combo box named "cmb1".
cmb1.datasource = dt

where dt is my data table.

This binding is done with in the formload() method. So once my form is loaded combobox is displayed with all items available in the data table dt and also i got a
button control named btn1 in the loaded form.

In btn1 click event i am changing the combo box selected value as,
cmb1.selectedvalue = 2;

This selected value change is subscribed my cmb1 selected value event method. Inside this method i am just getting the selected value
int nSelectedValue = (int)cmb1.selectedValue;

Now the issue is when i click btn1, as explained above selected value is changed to 2 and my cmb1 selected value change method is executed.
But Inside this selected value change method cmb1.selectedValue is showing as -1 instead of 2. Selected item is displayed as null even though my selected value is 2 and i got more than 10 items in it.

Please help to solve this

sometimes cmb1.selectedValue becomes null. So when i say
int nSelectedValue = (int)cmb1.selectedValue; it gives me error.

Thanks LittleBlackLui and OriginalGriff for your valued solutions.
Thank you very much
Share this answer
Hi cockyrabbit!

You need to check if page is PostBack at the Load.[^]

protected void Page_Load(object sender, EventArgs e)
    if (!Page.IsPostBack)
         cmb1.datasource = dt;

Other thing you need to check is the combobox EnableViewState prop. is set to true.

Share this answer
When you first load the table it has no selected items, so it throws a SelectedValueChanged event with an index of -1. It is likely that it also returns this as teh value if there is none at the time.

At the start of the event handler, check the index:
private void cbSource_SelectedValueChanged(object sender, EventArgs e)
    ComboBox cb = sender as ComboBox;
    if (cb != null && cb.SelectedIndex >= 0)
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900