如何在绑定到 DataTable 的 ComboBox 中插入“空"字段 [英] How to insert 'Empty' field in ComboBox bound to DataTable

查看:14
本文介绍了如何在绑定到 DataTable 的 ComboBox 中插入“空"字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WinForms 应用程序上有一个组合框,可以在其中选择一个项目,但这不是强制性的.因此,我需要一个空"的第一项来指示尚未设置任何值.

I have a combo box on a WinForms app in which an item may be selected, but it is not mandatory. I therefore need an 'Empty' first item to indicate that no value has been set.

组合框绑定到从存储过程返回的数据表(我不为我的 UI 控件上的匈牙利符号表示歉意:p):

The combo box is bound to a DataTable being returned from a stored procedure (I offer no apologies for Hungarian notation on my UI controls :p ):

 DataTable hierarchies = _database.GetAvailableHierarchies(cmbDataDefinition.SelectedValue.ToString()).Copy();//Calls SP
 cmbHierarchies.DataSource = hierarchies;
 cmbHierarchies.ValueMember = "guid";
 cmbHierarchies.DisplayMember = "ObjectLogicalName";

如何插入这样一个空项目?

How can I insert such an empty item?

我确实有权更改 SP,但我真的不想用 UI 逻辑污染"它.

I do have access to change the SP, but I would really prefer not to 'pollute' it with UI logic.

更新:我忽略了 DataTable.NewRow(),谢谢.我已经更新了你们所有人(到目前为止所有 3 个答案).在我决定答案"之前,我试图让迭代器模式正常工作

Update: It was the DataTable.NewRow() that I had blanked on, thanks. I have upmodded you all (all 3 answers so far anyway). I am trying to get the Iterator pattern working before I decide on an 'answer'

更新:我认为这个编辑让我进入了社区 Wiki 领域,我决定不指定一个单一的答案,因为它们在各自的领域都有优点.感谢您的集体投入.

Update: I think this edit puts me in Community Wiki land, I have decided not to specify a single answer, as they all have merit in context of their domains. Thanks for your collective input.

推荐答案

您可以做两件事:

  1. 向存储过程返回的DataTable添加一个空行.

DataRow emptyRow = hierarchies.NewRow();
emptyRow["guid"] = "";
emptyRow["ObjectLogicalName"] = "";
hierarchies.Rows.Add(emptyRow);

创建一个 DataView 并使用 ObjectLogicalName 列对其进行排序.这将使新添加的行成为 DataView 中的第一行.

Create a DataView and sort it using ObjectLogicalName column. This will make the newly added row the first row in DataView.

DataView newView =           
     new DataView(hierarchies,       // source table
     "",                             // filter
     "ObjectLogicalName",            // sort by column
     DataViewRowState.CurrentRows);  // rows with state to display

然后将dataview设置为ComboBoxDataSource.

Then set the dataview as DataSource of the ComboBox.

如果您真的不想如上所述添加新行.您可以允许用户通过简单地处理删除"按键事件来将 ComboBox 值设置为 null.当用户按下 Delete 键时,将 SelectedIndex 设置为 -1.您还应该将 ComboBox.DropDownStyle 设置为 DropDownList.因为这将阻止用户编辑 ComboBox 中的值.

If you really don't want to add a new row as mentioned above. You can allow the user to set the ComboBox value to null by simply handling the "Delete" keypress event. When a user presses Delete key, set the SelectedIndex to -1. You should also set ComboBox.DropDownStyle to DropDownList. As this will prevent user to edit the values in the ComboBox.

这篇关于如何在绑定到 DataTable 的 ComboBox 中插入“空"字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆