【发布时间】:2018-05-24 11:58:22
【问题描述】:
我正在尝试使用 VS2017 C# 根据 TextBox 中的值在 Combobox 中设置所选项目。 TextBox 填充了来自 BindingSource 的数据,这些数据传递给了 Form,而我正在使用来自单独查询的数据填充 ComboBox。这是表单构造函数
public Form2(BindingSource dataSource)
{
string DbConnectionString = @"Data Source=Emp.db;Version=3;";
SQLiteConnection dbc = new SQLiteConnection(DbConnectionString);
SQLiteDataAdapter DEPDataAdapter = new SQLiteDataAdapter("select * from DEPARTMENT", dbc);
DataSet DEPdata = new DataSet();
DEPDataAdapter.Fill(DEPdata, "DEPARTMENT");
InitializeComponent();
formDataSource = dataSource;
TextBoxfName.DataBindings.Add("Text", formDataSource, "FNAME", true);
TextBoxlName.DataBindings.Add("Text", formDataSource, "LNAME", true);
TextBoxDEP.DataBindings.Add("Text", formDataSource, "DEPNO".ToString(), true);
TextBoxComment.DataBindings.Add("Text", formDataSource, "Comment", true);
// ComboBoxDep.DataBindings.Add("DEPNO", formDataSource, "DEPNO");
// ComboBoxDEP.DataBindings.Add("DEPNAME", DEPdata.Tables["DEPARTMENT"], "DEPNO");
ComboBoxDEP.DataSource = DEPdata.Tables["DEPARTMENT"];
ComboBoxDEP.DisplayMember = "DEPNAME";
ComboBoxDEP.ValueMember = "DEPNO";
ComboBoxDEP.SelectedValue = Convert.ToInt32(TextBoxDEP.Text);
}
我收到以下错误:
System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Convert.ToInt32(String value)
参考ComboBoxDEP.SelectedValue = Convert.ToInt32(TextBoxDEP.Text);
这一行Department 表的 DepNo 类型为整数。我希望如果我基于 ComboBox 更改以编程方式更改 TextBox 的值,这也会影响 DataBinding。我还尝试了 ComboBox ValueMember 类型转换的许多变体,我不明白为什么这不起作用,它看起来很简单。
【问题讨论】:
-
您是否要根据 Id.. 选择它?该错误准确地告诉您错误/问题是什么。请更新问题并显示您尝试根据 selectedvalue 将下拉列表绑定到的查询中的哪一列。如果列是字符串,则 SelectedValue 将是字符串。如果您要绑定的列基于索引,例如 Id,则所选值是该列/字段,我也看不到
ComboBoxDEP.DataBind()方法 -
你没有调用 DataBind() 所以文本框文本很可能是空的,因此转换会抛出异常。
-
我以为以ComboBoxDEP.DataSource = DEPdata.Tables["DEPARTMENT"];开头的那一系列语句做了数据绑定,而不是在一次调用中设置所有这些。 ComboBox 不为空,它按应有的方式显示 DepName,并且我已经实现了 MetroFramework.MetroMessageBox.Show(this, ComboBoxDEP.SelectedValue.ToString(), "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);每当我更改组合框时,它都会显示组合框的选定值,即表中的列 DEPNO。但是,执行 ComboBoxDEP.SelectedValue 会产生类型转换错误。
-
作为另一个测试,只需硬编码 ComboBoxDEP.SelectedValue = 2;工作正常,它显示正确的 DataDisplayMemeber
标签: c# winforms combobox datasource