问题描述
如何为允许DBNull的ComboBox创建列表?
How to create a list for a ComboBox that allows DBNull?
我试过 int?但 int? >与 DBNull 不同,并且组合框不使用null值。
I tried int? But int? is not the same as DBNull and the combobox does not work with the null value.
我的datagridview组合框需要 DBNull 。
My datagridview combobox, needs DBNull.
>
I did:
var machineComboList = this.eMDataSet1.Machines.Select(row => new
{
Key = (int?) row.MachineID,
Value = row.Description
}).ToList();
int? nullValue = DBNull.Value;
machineComboList.Add(new { Key = nullValue, Value = "All" });
我想把一个DBNull值放入Key。 int 不起作用。
I want to put a DBNull value into "Key". Using int? does not work.
相关:
推荐答案
DBNull
仅适用于ADO.NET,以区分缺失值和空值。
DBNull
is only intended for ADO.NET, to make a distinction between a missing value and a null value.
int?
可以是 null
- 这可能是你要找的。它不能是 DBNull
,因为它们是不兼容的类型。
int?
can be null
-- this is probably what you're looking for. It can never be DBNull
, as they are incompatible types.
很少能直接使用 DBNull
以外的ADO.NET调用。从数据库中读取时,通常会这样翻译:
It is rare to work directly with DBNull
outside of ADO.NET calls. When reading from the database, you'll usually translate it like this:
object dbValue = ...;
int? intValue = dbValue != DBNull.Value ? (int)dbValue : (int?)null;
或者,如果你对返回的数据类型更加信任,你可以缩短到:
Or if you're a little more trusting of the data types returned, you can shorten it to this:
object dbValue = ...;
int? intValue = dbValue as int?;
这篇关于如何创建一个允许DBNull的ComboBox列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!