[英]C# Winform: Convert Combobox ValueMember Property to long
I have a combobox with Id,Name columns. 我有一个带有Id,Name列的组合框。 I have added these values to combobox with datatable:
我已经将这些值添加到带有数据表的组合框中:
DataTable.Rows.Add(1, "Name1");
DataTable.Rows.Add(2, "Name2");
Id column should be a long. id栏应该很长。 However when I tried to get the Id value, it says cannot convert to long:
但是,当我尝试获取Id值时,它说不能转换为long:
long id;
id = this.comboBox1.ValueMember;
How to do that ? 怎么做 ?
Thanks. 谢谢。
@BlueMonkMN, almost there but when I tried MessageBox.Show prints 1 (from my datatable values above) @BlueMonkMN,几乎在那儿,但是当我尝试MessageBox.Show打印出1(从上面的数据表值中获取)
MessageBox.Show(comboBox1.SelectedValue.ToString());
but this line 但是这条线
id = (long)(comboBox1.SelectedValue);
throws a cast exception ? 抛出强制转换异常?
Why 1 cannot be converted to long ? 为什么1不能转换为long?
First of all, make sure that a long integer is what you need. 首先,请确保您需要一个长整数。 A regular integer (int) is specified in the DataTable as a Systemn.Int32 and generally works best on 32-bit operating systems.
在DataTable中将常规整数(int)指定为Systemn.Int32,通常在32位操作系统上效果最佳。 The range of this integer is from -2,147,483,648 to 2,147,483,647.
该整数的范围是-2,147,483,648至2,147,483,647。 If in fact you need larger integers than that, then go ahead and use System.Int64 in the DataTable and long in your code.
如果实际上您需要的整数更大,那么请继续使用DataTable中的System.Int64,并在代码中使用长整数。
Next, you are trying to access the wrong property of the combo box. 接下来,您正在尝试访问组合框的错误属性。 You need to access the SelectedValue property.
您需要访问SelectedValue属性。 ValueMember is the property that determines which column/property of the bound object will be exposed by the SelectedValue property.
ValueMember是确定SelectedValue属性将公开绑定对象的哪个列/属性的属性。
Here is some code illustrating approximately how the combo box should be configured: (Generated code from InitializeComponent) 以下是一些代码,它们大致说明了组合框的配置方式:(从InitializeComponent生成的代码)
this.dataTable1BindingSource = new System.Windows.Forms.BindingSource(this.components);
this.dataSet11 = new WindowsFormsApplication1.DataSet1();
//
// comboBox1
//
this.comboBox1.DataSource = this.dataTable1BindingSource;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "id";
//
// dataTable1BindingSource
//
this.dataTable1BindingSource.DataMember = "DataTable1";
this.dataTable1BindingSource.DataSource = this.dataSet11;
And here's some code illustrating how you retrieve the selected value from the combo box, if in fact you want the id to be a long integer: 下面的代码说明了如何从组合框中检索选定的值,如果实际上您希望id为长整数:
long id = (long)(comboBox1.SelectedValue);
ValueMember is a string datatpye property and it represent a name of column. ValueMember是字符串datatpye属性,它表示列的名称。 OP must have to use SelectedValue property.
OP必须必须使用SelectedValue属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.