C# Checking string data in combobox displaymember

118 Views Asked by At

Here is:

Datatable dt;
......
.......
cmbName.DataSource=dt;
cmbName.ValueMember="ID";
cmbName.DisplayMember="Name";


private void cmbName_Validating(object sender, CancelEventArgs e)
{          
    if (cmbName.Text == string.Empty)
    {
        MessageBox.Show("select correct  name");
        e.Cancel = true;
    }
    else if (cmbName.Items.Contains(cmbName.Text))
    {
        e.Cancel = false;
    }
    else
    {
        MessageBox.Show("select correct name");
        e.Cancel = true;
    }
}

always shows 'select correct name'. Even it is selected from the dropdownlist. Please Can anybody suggest me!

2

There are 2 best solutions below

6
mdadil2019 On

According to your statement

If you your cmbname.Text is empty, it shows the Message:

select correct name

When your cmbname.Text is not empty then again it shows the Message:

select correct name

You have to specify in the else condition what message you want as an output when you select from the DropDownList.

0
Darpan Dahal On

I did it by this code, This may help somebody:

if (Convert.ToInt32(cmbName.SelectedValue) >= 1)
        {
            e.Cancel = false;

        }
        else
        {
            MessageBox.Show("select correct name");
            e.Cancel = true;
        }