0

I'm using C# win forms and I need to prevent paste into a combo box in that.(Prevent only if pasting string not in the drop down item list). If pasting string is a item in drop down list user should allow to paste it. I already prevent user attempt to enter non existing items.Below the code is provided

     private void listLocation_KeyPress(object sender, KeyPressEventArgs e)
     {
        if (Char.IsControl(e.KeyChar))
        {
            return;
        }
        ComboBox box = ((ComboBox)sender);

        string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);

        string text = nonSelected + e.KeyChar;
        bool matched = false;
        for (int i = 0; i < box.Items.Count; i++)
        {
            if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null))
            {
                matched = true;
                break;
            }
        }
        e.Handled = !matched;
    }
laalto
  • 150,114
  • 66
  • 286
  • 303
oshan2csd
  • 393
  • 4
  • 11
  • see this question, it will tell you how to hook into the paste event: http://stackoverflow.com/questions/3446233/hook-on-default-paste-event-of-winforms-textbox-control – Turch Jun 21 '13 at 12:47

1 Answers1

0

Try this ...

private void comboBox1_TextChanged(object sender, EventArgs e)
{
    // Called whenever text changes.
    if (combobox1.findstringexact(comboBox1.Text) > -1)
        {
        // codes if the text not in the lists
        } 
}
matzone
  • 5,703
  • 3
  • 17
  • 20
  • Could you please explain your answer more. what is findstringexact() method and how to implement it? – oshan2csd Jun 22 '13 at 10:50
  • @rocs .. what I know that findstringexact is methode to compare string we have with the list in combobox or listbox .. you can read it here .. http://msdn.microsoft.com/en-us/library/c440x2eb.aspx – matzone Jun 22 '13 at 12:46