简体   繁体   中英

Need some help of retrieving a single text from SQL database into a textbox in Visual Studio using C#

so I want to retrieve a text from SQL Database and place it into a text box. I have a combo-box in where I retrieve a list of last_names, and when the user selects the last name the Data Grid view is updated to contain information pertaining to that last name. Now as we all know there can always be a same last name but a different first name, so I wanted to get a text box that shows the first name. I've scoured a lot through the internet and found people using SQL Data Reader, and thought to try it myself, though whenever I ran it, the text-box is always empty after I select a name from the combo box.

Here's my code:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(@"my connection string");
        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter("SELECT Statement to update the dataview grid based on the user's pick of the last name", con);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        // populating dgv with data
        dataGridView1.DataSource = dt;

        //now attempting to get the textbox filled

        SqlCommand cmd = new SqlCommand("Select [Person_FirstName] from person where Person_LastName='" + comboBox1.ValueMember + "'", con);
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())

        {

            textBox1.Text = dr[0].ToString();
                            // tried dr["Person_FirstName"].ToString() and dr["[Person_FirstName]").ToString(), with still no text showing in the textbox
            dr.Close();
        }
        con.Close();
    }

If there is anyway to fix this please let me know as soon as possible! And thank you in advanced!

You can use this

 SqlConnection con = new SqlConnection(@"my connection string");
    con.Open();
    SqlDataAdapter sda = new SqlDataAdapter("Select [Person_FirstName]     from person where Person_LastName='" + comboBox1.ValueMember + "'", con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    DataRow dr=dt.Rows[0];    
    TextBox.Text=dr[0].ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM