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