防止将字符串粘贴到组合框中,这些组合框不是C#中该组合框的项目

时间:2013-06-21 11:07:11

标签: winforms visual-studio-2010 c#-4.0

我正在使用C#win表单,我需要阻止粘贴到其中的组合框中。(仅当粘贴不在下拉项列表中的字符串时才阻止)。如果粘贴字符串是下拉列表中的项目,则用户应允许粘贴它。 我已经阻止用户尝试输入非现有项目。下面提供了代码

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

1 个答案:

答案 0 :(得分:0)

试试这个......

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
        } 
}
相关问题