Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected ComboBox to Text Box

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.

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.

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();
    }
}
like image 779
Chris Turner Avatar asked Dec 05 '22 15:12

Chris Turner


1 Answers

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

textBox1.Text = comboBox1.Text;
like image 89
Jaime Torres Avatar answered Dec 10 '22 11:12

Jaime Torres