C# 选定的组合框到文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11582648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:27:10  来源:igfitidea点击:

Selected ComboBox to Text Box

c#winformsvisual-studio-2010combobox

提问by Chris Turner

I am working on creating a form which pulls data from a database, and supplies two combo boxes. ComboBox1 shows Employee name in a "First name Last Name" format. ComboBox2 shows the Employee names in "Last, First" format. The names are pulling into the combo boxes without any difficulty.

我正在创建一个从数据库中提取数据的表单,并提供两个组合框。ComboBox1 以“名字姓氏”格式显示员工姓名。ComboBox2 以“Last, First”格式显示员工姓名。这些名称毫无困难地进入了组合框。

What I am attempting to figure out how to do is once a user selects a name from either of the drop down boxes that it will populate certain text boxes such as, textBox1, textBox2 based on other information from the Query.

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

I have attempted to use

我曾尝试使用

textBox1.Text = comboBox1.SelectedItem;

however, I get an error stating: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

但是,我收到一条错误消息:无法将类型“对象”隐式转换为“字符串”。存在显式转换(您是否缺少演员表?)

Here is my current code. I have left out the connection queries to databases and such intentionally.

这是我当前的代码。我故意省略了对数据库的连接查询等。

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();
    }
}

采纳答案by LarsTech

In your SelectedIndexChanged event, add the code:

在 SelectedIndexChanged 事件中,添加代码:

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

You should probably remove this statement from your while loop:

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

// textBox1.Text = comboBox1.SelectedItem;

because you just added the item to the ComboBox items collection, but you don't actually know it's been selected.

因为您刚刚将该项目添加到 ComboBox 项目集合中,但您实际上并不知道它已被选中。

Also, make sure you wire the event up:

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

public Employees()
{
  InitializeComponent();

  // yada-yada-yada

  comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}

回答by Spacemancraig

What you need is to use the TEXT value so instead of textBox1.Text = comboBox1.SelectedItem;It should be textBox1.Text = comboBox1.SelectedItem.ToString();or simply textBox1.Text = comboBox1.Text

您需要的是使用 TEXT 值,而不是textBox1.Text = comboBox1.SelectedItem;It should betextBox1.Text = comboBox1.SelectedItem.ToString();或简单地textBox1.Text = comboBox1.Text

回答by Jaime Torres

If all you need is the text, you can simply use:

如果您只需要文本,则可以简单地使用:

textBox1.Text = comboBox1.Text;

回答by dtsg

You need to use:

您需要使用:

textBox1.Text = comboBox1.SelectedItem.Textto get the text part of the item.

textBox1.Text = comboBox1.SelectedItem.Text获取项目的文本部分。

SelectedItemis an object and you're trying to assign it to the Textproperty of the text box.

SelectedItem是一个对象,您正试图将其分配给Text文本框的属性。

回答by Olivier Jacot-Descombes

Since you can fill a ComboBoxwith items of any type (not just string) the SelectedItemproperty has a type of object. If you inserted stringsyou can retrieve them by casting

由于您可以ComboBox使用任何类型(不仅仅是string)的项目填充 a ,因此该SelectedItem属性的类型为object。如果您插入,strings您可以通过投射来检索它们

string s = (string)myComboBox.SelectedItem;

If you added items of some other type like a class Person, you can either retrieve this object or get its string or some property with

如果添加了其他类型的项目,如类Person,则可以检索此对象或获取其字符串或某些属性

Person p = (Person)myComboBox.SelectedItem;
string s = myComboBox.SelectedItem.ToString();
string lastName = ((Person)myComboBox.SelectedItem).LastName;

回答by Josko

Unfortunatly you can't do this:

不幸的是,你不能这样做:

textBox1.Text = comboBox1.SelectedItem.ToString();

because the result is also path:

因为结果也是路径:

System.Windows.Controls.ComboBoxItem: Citroen

You need only value for example Citroen

您只需要价值,例如雪铁龙

So problem can be resolved by searching for string like this:

所以问题可以通过搜索这样的字符串来解决:

      string auto = comboBox1.SelectedItem.ToString();
      int index = auto.IndexOf(" ");
      carModel.Text = auto.Substring(index+1);