只读Windows窗体组合框
问题描述:
答
您可以设置DropDownStyle为DropDownList,但并没有真正让打字(但它允许用键盘选择)。
如果您确实希望用户能够键入/查看不完整的单词,则必须使用事件。验证事件将是最佳选择。
答
如果您在用户键入内容时设置了AutoCompleteMode = SuggestAppend
和AutoCompleteSource = ListItems
,则自动显示以打字字符开头的条目。
然后通过处理SelectedIndexChanged
或SelectedValueChanged
事件,您将能够在用户键入值列表中的某个值时截取。
如果你也绝对不希望用户输入任何东西,这不是在列表中,那么是的,你必须处理例如KeyDown
事件,如:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
char ch = (char)e.KeyValue;
if (!char.IsControl(ch))
{
string newTxt = this.comboBox1.Text + ch;
bool found = false;
foreach (var item in this.comboBox1.Items)
{
string itemString = item.ToString();
if (itemString.StartsWith(newTxt, StringComparison.CurrentCultureIgnoreCase))
{
found = true;
break;
}
}
if (!found)
e.SuppressKeyPress = true;
}
}
+0
谢谢,我害怕我必须这样做! – 2010-10-03 13:58:38
答
感谢。除了KeyDown事件代码之外,上面的方法适用于我。因为组合框附加到DataTable。如果将组合框附加到DataTable上,请尝试下面的代码,并且如果您也绝对不希望用户键入不在列表中的任何内容。
private void cmbCountry_KeyDown(object sender, KeyEventArgs e)
{
char ch = (char)e.KeyValue;
if (!char.IsControl(ch))
{
string newTxt = this.cmbCountry.Text + ch;
bool found = false;
foreach (var item in cmbCountry.Items)
{
DataRowView row = item as DataRowView;
if (row != null)
{
string itemString = row.Row.ItemArray[0].ToString();
if (itemString.StartsWith(newTxt, StringComparison.CurrentCultureIgnoreCase))
{
found = true;
break;
}
}
else
e.SuppressKeyPress = true;
}
if (!found)
e.SuppressKeyPress = true;
}
}
谢谢!我只是想我可以不用自己编码...猜猜我的另一个库组件... – 2010-10-03 13:59:23