C# 将ComboBox SelectedValue设置为TextBox值

C# 将ComboBox SelectedValue设置为TextBox值,c#,winforms,combobox,datasource,C#,Winforms,Combobox,Datasource,我正在尝试使用VS2017 C根据文本框中的值在组合框中设置所选项。文本框中填充了来自传递到表单的BindingSource的数据,并且我正在使用来自单独查询的数据填充组合框。这是表单构造函数 public Form2(BindingSource dataSource) { string DbConnectionString = @"Data Source=Emp.db;Version=3;"; SQLiteConnection dbc = new SQLiteConne

我正在尝试使用VS2017 C根据文本框中的值在组合框中设置所选项。文本框中填充了来自传递到表单的BindingSource的数据,并且我正在使用来自单独查询的数据填充组合框。这是表单构造函数

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)
参考行ComboxDep.SelectedValue=Convert.ToInt32TextBoxDEP.Text


Department表的DepNo类型为整数。我希望如果我根据ComboBox的更改对TextBox的值进行渐进式更改,也会影响数据绑定。我还尝试了许多关于组合框ValueMember类型转换的变体,我不明白为什么这不起作用,它看起来很简单。

好的,修复了这个问题。我没有使用TextBox值,而只是使用BindingSource

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

现在,我在ComboBoxDEP_SelectedValueChanged方法中有了代码,可以在ComboBox值更改时执行某些操作

您是否试图根据Id选择它。。?该错误准确地告诉您错误/问题是什么。。请根据selectedvalue更新问题并显示您试图将下拉列表绑定到查询中的哪一列。如果列是字符串,则SelectedValue将是字符串。。如果您要绑定的列基于索引,例如Id,那么所选的值是该列/字段,我没有看到ComboxDep.DataBind方法。如果您没有调用DataBind,则文本框文本很可能为空,因此转换将引发异常。我认为这一系列语句使用ComboBoxDEP.DataSource=DEPdata.Tables[DEPARTMENT];进行数据绑定,而不是在一次调用中设置所有数据绑定。ComboBox不是空的,它按应有的方式显示DepName,我已经实现了MetroFramework.MetroMessageBox.Showthis,ComboBoxDEP.SelectedValue.ToString,OK,MessageBoxButtons.OK,MessageBoxIcon.Information;它显示组合框的选定值,即每当我更改组合框时,表中的DEPNO列。但是,执行ComboBoxDEP.SelectedValue会产生类型转换错误;工作正常,它显示正确的DataDisplayMemeber