简体   繁体   English

ComboBox选定值为空白

[英]ComboBox Selected Value to be Blank

Uses: VS 2012; 用途:VS 2012;

I've a combobox attached to a datasource in my form. 我有一个组合框附加到表单中的数据源。 And things work fine. 一切正常。 When I run the form, again everything works fine; 当我运行表单时,一切都再次正常运行; I can select an item in the dropdown list and it updates to the datasource as well. 我可以在下拉列表中选择一个项目,它也会更新到数据源。 My problem comes when I need to deselect/revert what I have selected after I saved or Remove what I have select (basically should go as null for that field value). 我的问题是当我需要在保存或删除我选择的内容后取消选择/还原选择的内容时(对于该字段值,基本上应该为null )。

Our legacy system was built in Delphi 3 & 5 , and users got a feature of right-clicking on the dropdown list and get a small popup like button named 我们的旧系统是在Delphi 3和5中构建的,用户具有在下拉列表上单击鼠标右键的功能,并且获得了一个小的弹出窗口,例如名为

Blank 空白

which blanks what have been selected. 哪些空白已被选中。 I could not find anything that will do the same what ever user have selected in .NET's combo box. 我找不到能与用户在.NET组合框中选择的功能相同的功能。

You can add a new item in dropdown named -Select- ( or something similar name) by using following code: 您可以使用以下代码在名为-Select- (或类似名称)的dropdown添加新项目:

drp.DataSource = dataSet;
drp.DataBind();
// do it after binding
    drp.Items.Insert(0, new ListItem("-Select-", "NA"));

If you are binding in xaml then on page_load event you can write only this line 如果您绑定在xaml中,则在page_load事件中,您只能写此行

 drp.Items.Insert(0, new ListItem("-Select-", "NA"));

Now if user want to deselect choice, he/she will simply select -Select- item. 现在,如果用户要取消选择选项,则只需选择-Select-项目。

Whilst thanking all of your Answers and suggestions, I used @V4Vendetta's idea and composed my solution. 在感谢您所有的答案和建议的同时,我使用了@ V4Vendetta的想法并制定了解决方案。

Similarly to deleting a record in a datagridview where you click Delete key, I took the same concept and associated my solution with Delete Key. 与删除datagridview中的记录(单击Delete键)相似,我采用了相同的概念并将我的解决方案与Delete Key相关联。

What I did was created a handler for ComboBox's Keypress Event like: 我所做的是为ComboBox的Keypress事件创建了一个处理程序,例如:

private void comboBox_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
            (sender as ComboBox).SelectedIndex = -1;    
    }
}

And linked to every ComboBox's available 并链接到每个可用的ComboBox

ComboBox1.KeyDown += new KeyEventHandler(comboBox_KeyPress);
ComboBox2.KeyDown += new KeyEventHandler(comboBox_KeyPress);

Now when user clicks Delete key while the ComboBox selected/active, it gets blank. 现在,当用户在组合框处于选中/活动状态时单击“ 删除”键时,它将变为空白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM