Home > Mobile >  Iam currently working on a book managment project and im using sql server from Visual studio, I have
Iam currently working on a book managment project and im using sql server from Visual studio, I have

Time:02-12

Iam currently working on a book management project and I'm using SQL Server from Visual Studio. I have a Book Category table in the database and I'm trying to place it in a combobox.

This the code - I don't see anything wrong with it but the categories are taking so long to be visible in the combobox.

Also the list is repetitive, is it maybe because of the while Loop? If so is there any way to fix it?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\malek\source\repos\BookStore\BookStore\BOOKDB.mdf;Integrated Security=True");
                scmd.Connection = con;
                con.Open();
                scmd.CommandText = "SELECT CATEGORY FROM BOOKCAT";
                var rd = scmd.ExecuteReader();
                while (rd.Read())
                {
                    List.Add(Convert.ToString(rd[0]));
                }
                int i = 0;
                while (i < List.LongCount())
                {
                    comboBox1.Items.Add(List[i]);
                    i = i   1;
                }

            }
            catch (Exception EX)
            {

                MessageBox.Show(EX.Message);
            }
            finally
            {
                con.Close();
            }
        }

What did I miss?

NOTE: I am not getting any errors!!

CodePudding user response:

Based on the code you've posted, it looks like you're loading the categories from the database in the SelectedIndexChanged event of comboBox1.

So, every time you choose a new item from comboBox1 you're executing this code; you're going to the database and loading everything from the BOOKCAT table and you're putting those items into List and comboBox1. That is why you're seeing duplicated categories. It's probably also why it takes so long for a category to be visible in the ComboBox.

You probably don't want to load the ComboBox items from the database every time the selected index changes, so you should do that somewhere else. For example, you could do it in the Form's constructor, or in the 'Load' event.

  • Related