将ComboBox SelectedValue设置为TextBox值

时间:2017-12-11 00:06:04

标签: c# winforms combobox datasource

我正在尝试使用VS2017 C#基于TextBox中的值在Combobox中设置所选项目。 TextBox填充了传递给Form的BindingSource的数据,我用一个单独的查询中的数据填充ComboBox。这是Form构造函数

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的类型转换的许多变化,我不明白为什么这不起作用,它看起来很简单。

1 个答案:

答案 0 :(得分:0)

好的,修好了。而不是使用TextBox值,它总是看起来有点cludgy,我只是使用BindingSource

ComboBoxDEP.SelectedValue = ((DataRowView)this.formDataSource.Current).Row["DEPNO"];

我现在在ComboBoxDEP_SelectedValueChanged()方法中有代码,以便在ComboBox值更改时执行某些操作。