如何插入'空'字段的组合框绑定到数据表 [英] How to insert 'Empty' field in ComboBox bound to DataTable

查看:113
本文介绍了如何插入'空'字段的组合框绑定到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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(),我已经上空白,谢谢。我已经upmodded大家(所有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. 添加一个空行到数据表是从存储过程返回。

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



创建一个数据视图,并使用ObjectLogicalName列排序。这将使新添加的行中第一行数据视图。

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



然后设置数据视图为数据源组合框

如果你真的不希望添加新的行,如上所述。您可以允许用户通过简单的操作删除按键事件将组合框值设置为空。当用户按下删除键,设置的SelectedIndex 为-1。您还应该设置 ComboBox.DropDownStyle 的DropDownList 。因为这将阻止用户在组合框来编辑值。

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.

这篇关于如何插入'空'字段的组合框绑定到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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