简体   繁体   中英

Using data from database in Visual Studio 2015

I am trying to make a POS application in MS VS 2015. I have created the database in MS SQL Management studio and am now trying to call it in VS 2015. More specifically trying to show the data in a combo box in windows form app. I did the following:

public partial class Form1 : Form
{
   private Coffee_shopEntities cse = new Coffee_shopEntities();

   public Form1()
   {
       InitializeComponent();
   }

   private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
   {
       comboBox1.DataSource = cse.tblProductTypes;
       comboBox1.DisplayMember = "Description";
       comboBox1.ValueMember = "ProductType";
   }
}

But nothing shows up in the combo box , it's still empty.
And yes the table has values stored in it.

Why are you doing this in the SelectedIndexChanged event? If the control never has items in the first place, how is the selected index going to change?

Populate the control when the form loads:

public Form1()
{
    InitializeComponent();
    Load += new EventHandler(Form1_Load); // or use the form designer
}

private void Form1_Load(object sender, System.EventArgs e)
{
    comboBox1.DataSource = cse.tblProductTypes;
    comboBox1.DisplayMember = "Description";
    comboBox1.ValueMember = "ProductType";
}

The SelectedIndexChanged is invoked by the control itself when a user changes the selected item. It's not where you would initially populate the control with items. (Though you can use it to re-populate the control with different items when one is selected. That would be a pretty jarring UX however.)

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