obrienkev

Hi,

I want to set a variable if a ComboBox has been selected.

I initially set comboBox to...

Code Snippet

myNameComboBox.Text = "Select Name";

Then I want to check if the user has chosen from the ComboBox list...

Code Snippet

string myName;
if (myNameComboBox.SelectedItem != null)
{
myName = myNameComboBox.SelectedValue.ToString();
MessageBox.Show(myName);
}
else
{
myName = null;
}

However, myName is not set to null when the user does not select from the ComboBox.

Why is this

The comboBox is databound and DisplayMember, ValueMember and SelectedValue are all set.

Thanks.



Re: Visual C# Express Edition ComboBox Null Issue

bdorman

If myName is not set to null then there are really only three possible reasons why:

1. You never run the code above.
2. You run the code but myComboBox.SelectedItem is not null
3. You set myName to some value after it's set to null

When does that code run, is it on an event Have you tried stepping through with the debugger and watching your variables




Re: Visual C# Express Edition ComboBox Null Issue

obrienkev

Hi,

It becomes null only when I click on the ComboBox.

What should I do

The ComboBox functions are inside this function...

Code Snippet

private void searchButton_Click(object sender, EventArgs e)

{

...

}

Thanks.





Re: Visual C# Express Edition ComboBox Null Issue

Figo Fei - MSFT

Hi, obrienkev

Try the following code:

Code Snippet

string myName;
if (myNameComboBox.SelectedIndex>=0)
{
myName = myNameComboBox.SelectedItem.ToString();

//OR

myName = myNameComboBox.SelectedValue.ToString();
MessageBox.Show(myName);
}
else
{
myName = null;
}

Thanks






Re: Visual C# Express Edition ComboBox Null Issue

obrienkev

This works anyway...

Code Snippet

securityNameComboBox.Text = "Select Security Name";

string securityName = "";

if (securityNameComboBox.Text != "Select Security Name")

{

securityName = securityNameComboBox.SelectedValue.ToString();

}

else

{

securityName = null;

}