选中ComboBox到文本框

Chr*_*ner 4 c# combobox visual-studio-2010 winforms

我正在创建一个从数据库中提取数据的表单,并提供两个组合框.ComboBox1以"名字姓氏"格式显示员工姓名.ComboBox2以"Last,First"格式显示Employee名称.这些名字毫不费力地进入组合框.

我试图弄清楚如何做的是,一旦用户从下拉框中选择一个名称,它将根据查询中的其他信息填充某些文本框,例如textBox1,textBox2.

我试图使用

textBox1.Text = comboBox1.SelectedItem;
Run Code Online (Sandbox Code Playgroud)

但是,我得到一个错误说明:不能隐式地将类型'object'转换为'string'.存在显式转换(您是否错过了演员?)

这是我目前的代码.我故意遗漏了对数据库的连接查询.

public partial class Employees : Form
{
    public Employees()
    {
        InitializeComponent();

        //Connect to database for Employees Table Headers
        SqlConnection myConnection = new SqlConnection(@"Server=Server...");

        try {
            myConnection.Open();
            string SqlDataPull = String.Format("SELECT * FROM Employees WHERE Lname IS NOT NULL {0} ORDER By Lname", (checkBox1.Checked ? "AND Active='Y'" : ""));
            SqlCommand cmd = new SqlCommand(SqlDataPull, myConnection);
            cmd.CommandType = CommandType.Text;
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read()) {
                string strEmployee = String.Format("{0}  {1}", dr["Fname"], dr["Lname"]);
                comboBox1.Items.Add(strEmployee);
                textBox1.Text = comboBox1.SelectedItem;
                string strEmployee2 = String.Format("{0}, {1}", dr["Lname"], dr["Fname"]);
                comboBox2.Items.Add(strEmployee2);
            }
        } catch (Exception e) {
            MessageBox.Show(e.ToString());
        } finally {
            if (myConnection != null) {
                myConnection.Dispose();
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Main myNewForm = new Main();
        myNewForm.Show();
        this.Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Reports myNewForm = new Reports();
        myNewForm.Show();
        this.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jai*_*res 5

如果你需要的只是文字,你可以简单地使用:

textBox1.Text = comboBox1.Text;
Run Code Online (Sandbox Code Playgroud)


Lar*_*ech 5

在您的SelectedIndexChanged事件中,添加代码:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  if (comboBox1.SelectedIndex == -1) {
    textBox1.Text = string.Empty;
  } else {
    textBox1.Text = comboBox1.SelectedItem.ToString();
  }
}  
Run Code Online (Sandbox Code Playgroud)

您可能应该从while循环中删除此语句:

// textBox1.Text = comboBox1.SelectedItem;
Run Code Online (Sandbox Code Playgroud)

因为您只是将项目添加到了ComboBox项目集合中,但实际上并不知道已选择了该项目。

另外,请确保将事件连接起来:

public Employees()
{
  InitializeComponent();

  // yada-yada-yada

  comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}
Run Code Online (Sandbox Code Playgroud)