【发布时间】: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;
}
【问题讨论】:
-
看到这个问题,它会告诉你如何挂钩粘贴事件:stackoverflow.com/questions/3446233/…
标签: winforms visual-studio-2010 c#-4.0