【问题标题】:Prevent Paste strings into Combo Box which are not items of that Combo Box in C#防止将字符串粘贴到 C# 中不是该组合框的项目的组合框中
【发布时间】:2013-06-21 23:18:49
【问题描述】:

我正在使用 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;
    }

【问题讨论】:

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


【解决方案1】:

试试这个...

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

【讨论】:

  • 您能否解释一下您的答案。什么是 findstringexact() 方法以及如何实现?
  • @rocs .. 我知道 findstringexact 是将我们拥有的字符串与组合框或列表框中的列表进行比较的方法 .. 你可以在这里阅读 .. msdn.microsoft.com/en-us/library/c440x2eb.aspx
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
相关资源
最近更新 更多