1

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!

  • So you need to the user to not be able to write something in the combo that is not in its items. Does it need to be able to wirte at all? Why nor use the dropdown property? – Aimnox May 30 '16 at 08:02

2 Answers2

0

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;
        }
-1

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.

Draken
  • 3,134
  • 13
  • 34
  • 54
mdadil2019
  • 807
  • 3
  • 12
  • 29
  • It says that if it is empty it shows the msg, if its not empty NOR `(cmbName.Items.Contains(cmbName.Text))`it shows it too – Aimnox May 30 '16 at 08:01
  • Thanks for the comment and why: else if (cmbName.Items.Contains(cmbName.Text)) { e.Cancel = false; } is not working? – Darpan Dahal May 30 '16 at 08:05
  • if (cmbName.Text == string.Empty) { MessageBox.Show("select correct name1"); e.Cancel = true; } else { if (cmbName.Items.Contains(cmbName.Text)) { e.Cancel = false; } else { MessageBox.Show("select correct name2"); e.Cancel = true; } } also not working.Why?? – Darpan Dahal May 30 '16 at 08:08
  • @DarpanDahal When you select something from dropdownlist then cmbName.Test != empty so else is executed and here the compiler first check the if condition and that is true that is cmbName.Items.Contains(What you selected from dropdownlist) so here e.Calcel = false and the compiler not goes for next else statement. – mdadil2019 May 30 '16 at 08:16
  • @Mohammad Actually I'd like to make user able to type and display suggest items from the combobox items. And, if user leaves empty or the item is not in the list it shows the error message otherwise no action. In the above question the statement: cmbName.Items.Contains(cmbName.Text) doesn't find the cmbname.text, so how we can check the displaymember instead cmbname.items. – Darpan Dahal May 30 '16 at 08:26
  • try to use this.cmbName.DisplayMembers instead of cmbName.Text – mdadil2019 May 30 '16 at 08:37