[英]How to cast selectedvalue of combobox to an integer?
I have a combo box which was filled by datasource (value and id)我有一个由数据源(值和 ID)填充的组合框
comboBox_Degree.DataSource = ds.Tables["Field"];`
comboBox_Degree.DisplayMember = "Field_Degree";
comboBox_Degree.ValueMember = "Field_ID";
now I want to retreive id when SelectedIndexChanged event occur.现在我想在 SelectedIndexChanged 事件发生时检索 id。 but when I cast it to an int I have such this error.
但是当我将它转换为 int 时,我有这样的错误。
int fid = Convert.ToInt32(comboBox_Degree.SelectedValue.ToString());
error:错误:
Input string was not in a correct format.
输入字符串的格式不正确。
how can I cast this value to integer?如何将此值转换为整数?
Use this:用这个:
int fid;
bool parseOK = Int32.TryParse(comboBox_Degree.SelectedValue.ToString(), out fid);
I usually do something like我通常做类似的事情
int fid=0;
try {
fid=int.Parse(comboBox_Degree.SelectedValue.ToString());
} catch (Exception e)
{
//Whatever you want to do when it is not an int
}
您可以使用此代码来解决您的问题:
int id = Convert.ToInt32(comboBox_Degree.SelectedValue.GetHashCode());
I experienced the same problem and I found that setting the cbxExampleComboBox.DataSource
first then setting the cbxExampleComboBox.ValueMember
and cbxExampleComboBox.DisplayMember
second is the reason why when you call cbxExampleComboBox.SelectedValue
returns an object.我遇到了同样的问题,我发现首先设置
cbxExampleComboBox.DataSource
然后设置cbxExampleComboBox.ValueMember
和cbxExampleComboBox.DisplayMember
其次是调用cbxExampleComboBox.SelectedValue
返回对象的原因。
Setting the cbxExampleComboBox.ValueMember
and cbxExampleComboBox.DisplayMember
then cbxExampleComboBox.DataSource
will return int
if the type of cbxExampleComboBox.SelectedValue
is int
.设置
cbxExampleComboBox.ValueMember
和cbxExampleComboBox.DisplayMember
然后cbxExampleComboBox.DataSource
将返回int
,如果类型cbxExampleComboBox.SelectedValue
是int
。
Changing the code to the following should return the result as int
assuming that Field_ID
is of int
type假设
Field_ID
是int
类型,将代码更改为以下应将结果返回为int
comboBox_Degree.ValueMember = "Field_ID";
comboBox_Degree.DisplayMember = "Field_Degree";
comboBox_Degree.DataSource = ds.Tables["Field"];
I was having a similar problem.我遇到了类似的问题。 However, the issue was due to the combobox setup phase firing the eventhandler.
但是,问题是由于组合框设置阶段触发了事件处理程序。 So, I moved the
SelectedIndexChanged
EventHandler add from the Form.Designer
to the FormLoad
Event after the combobox setup (DataSource, ValueMember and DisplayMember assignments).所以,我感动
SelectedIndexChanged
从事件处理程序添加Form.Designer
到FormLoad
组合框设置(数据源,ValueMember和DisplayMember分配)后,事件。
// Example Combobox for Roles
DataTable dtRoles = new DataTable();
dtRoles = labDAO.GetRoles();
cbxRoleID.DataSource = dtRoles;
cbxRoleID.ValueMember = "ID";
cbxRoleID.DisplayMember = "Name";
cbxRoleID.SelectedIndexChanged += cbxRoleID_SelectedIndexChanged;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.