简体   繁体   中英

C# - Pull SQL data to textboxes/labels from changing combobox selected item

So I'm trying to create sort of an overview utility of sites, with different infos on each site.

I'd like to have a dropdown list / combobox, reading a sqldb and create items according to the db. Then I would like different textboxes to get populated with a value from a column.

Say my db table is called "AvSites" so far (just for the sake of it) i have "projectNr", "siteName", "siteClients" and "siteLicenses" columns I'd like each of these to populate some textbox / label somewhere.

I've tried the following, which kinda works, Ive had the code working most of the time, but the thing that defeats me is having the data change with the combobox item selected.

I hope you can help, and so here is my code so far (I have a login window, before this "main" program starts, just so you're not wondering)

And I'm quite new to C# so if there's something thats done inefficient thats the reason :) Im still learning.

namespace AvOverview{

public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        //btn_LogOut Click Event
        this.Hide();
        Form1 fl = new Form1();
        fl.Show();
    }

    private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        Application.Exit();
    }

    private void FrmMain_Load(object sender, EventArgs e)
    {
        string cs = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";

        SqlConnection con = new SqlConnection(cs);
        con.Open();
        string strCmd = "select * from AvSites";
        SqlCommand cmd = new SqlCommand(strCmd, con);
        SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        combo1.ValueMember = "id";
        combo1.DisplayMember = "siteName";
        combo1.DataSource = ds.Tables[0];
        combo1.Enabled = true;
        this.combo1.SelectedIndex = -1;
        cmd.ExecuteNonQuery();
        con.Close();
    }

    private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
    {

                 string cs = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
                 string strCmd = "select id from AvSites";
                 SqlConnection con = new SqlConnection(cs);
                 SqlCommand cmd = new SqlCommand(strCmd, con);
                 con.Open();
                 SqlDataReader dr = cmd.ExecuteReader();

                 while (dr.Read())

                 {//this last part is solely for testing if the text changed the way I wanted.

                     label1.Text = dr.GetValue(1).ToString();

                     label2.Text = dr.GetValue(2).ToString();
                     label3.Text = dr.GetValue(0).ToString();
                     label4.Text = dr.GetValue(3).ToString();

You don't need to call the database again. All the info are in the current selected item.
When you set the DataSource of your combo to a datatable like you do in the click event each element of the combo is a DataRowView and from this element you can get all the info extracted from the database from your initial query

private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
     DataRowView rv = Combo1.SelectedItem as DataRowView;
     if(rv != null)
     {
         label1.Text = rv[1].ToString();
         label2.Text = rv[2].ToString();
         label3.Text = rv[0].ToString();
         label4.Text = rv[3].ToString();
     }
}

Side note: There are some improvements needed in your code.
First you should store the connection string in the config file and read it back with the ConfigurationManager class. Read about Configuration in NET
Second you shouldn't work with disposable objects like you do now. A disposable object should be disposed as soon as you have finished to use it. In particular the SqlConnection keeps valuable system resources both on your machine and on the server. You should start to use the using statement

string strCmd = "select * from AvSites";
using(SqlConnection con = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(strCmd, con)))
{
    con.Open();
    SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    combo1.ValueMember = "id";
    combo1.DisplayMember = "siteName";
    combo1.DataSource = ds.Tables[0];
    combo1.Enabled = true;
    this.combo1.SelectedIndex = -1;
    // ??? not needed ==> cmd.ExecuteNonQuery();
    // not needed with using ==> con.Close();
}
// Here the connection is closed and disposed and resources are released

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