2010-10-03 74 views
2

有没有办法让windows窗体组合框只读? 具体说明:用户应该可以输入,但只允许输入框中的值(使用自动完成或从列表中选择)。只读Windows窗体组合框

或者是使用验证事件的唯一方法?

问候

马里奥

回答

3

您可以设置DropDownStyle为DropDownList,但并没有真正让打字(但它允许用键盘选择)。

如果您确实希望用户能够键入/查看不完整的单词,则必须使用事件。验证事件将是最佳选择。

+0

谢谢!我只是想我可以不用自己编码...猜猜我的另一个库组件... – 2010-10-03 13:59:23

3

如果您在用户键入内容时设置了AutoCompleteMode = SuggestAppendAutoCompleteSource = ListItems,则自动显示以打字字符开头的条目。

然后通过处理SelectedIndexChangedSelectedValueChanged事件,您将能够在用户键入值列表中的某个值时截取。

如果你也绝对不希望用户输入任何东西,这不是在列表中,那么是的,你必须处理例如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

0

感谢。除了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; 
     } 
    }