Click here to Skip to main content
16,012,843 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to be able to copy the contents of a table field (column) into a combobox so that a user can select directly from there without me entering the combobox values during its design

What I have tried:

private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection bscn = new SqlConnection("Data Source=PV10\\LOCALSERVER;Initial Catalog=SmallSoftwareDB;Integrated Security=True;Pooling=False");
                string ins = "insert into BulkSale(ProductSource, Date, Quantity, Type, UnitPrice, Total) values('" + textBox2.Text + "', '" + dateTimePicker1.Value + "', '" + textBox3.Text + "', '" + comboBox1.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "' )";
                string sPN = "select ProductName from BulkInput";
                SqlCommand P = new SqlCommand(sPN, bscn);
                comboBox2.DataSource = P.BeginExecuteReader();
                SqlCommand scmd = new SqlCommand(ins, bscn);
                bscn.Open();
                scmd.ExecuteNonQuery();
                MessageBox.Show("Successfully Completed.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                bscn.Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, " ", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            }
        } 
Posted
Updated 19-Sep-16 0:00am
v2

For starters, don't do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

Second, You need to open the connection before you try to use the reader.

Third, don't use a DataReader - they need everything alive while they are running, and your connection is closed before the combobox can load. Use a DataAdapter and a DataTable instead:
try
    {
    using (SqlConnection con = new SqlConnection(strConnect))
        {
        con.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT ProductName FROM BulkInput", con))
            {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                DataTable dt = new DataTable();
                da.Fill(dt);
                myComboBox.DataSource = dt;
                myComboBox.DisplayMember = "ProductName";
                }
            }
        }
    }
catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }


Always try to keep the connection string inside the configuration file (app.config or web.config, in your case it will be app.config). Say, if you have the key named as "conn" in the config file, you can fetch the value as below
string strConnect = ConfigurationManager.ConnectionStrings["conn"].ToString();
 
Share this answer
 
v2
Comments
Nganku Junior 18-Sep-16 9:16am    
Thanks for the proposed solution. I still applied your corrections with little success. You said Always try to keep the connection string inside the configuration file (app.config or web.config, in your case it will be app.config). Say, if you have the key named as "conn" in the config file
" where do I find this file? Plus I tried defining the StrConnect I cat get the ConfigurationManager.ConnectionStrings method where exactly do I Define it ?
OriginalGriff 18-Sep-16 10:01am    
I didn't - that was added to my solution.
It's good advice though - but exactly where to keep it will depend on the environment you are working in.
For WinForms, I'd suggest the settings.settings branch of your project properties:
https://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx
C#
try
           {
               using (SqlConnection con = new SqlConnection(ConString))
               {
                   SqlConnection con = new SqlConnection(CS);
                   con.Open();
                   string str = "SELECT ProductName FROM BulkInput";
                   cmd = new SqlCommand(str, con);
                   DataTable dTable = new DataTable();
                   DataRow dr;
                   SqlDataAdapter da = new SqlDataAdapter(cmd);
                   da.Fill(dTable);

                   //if you want to insert or validate as '--select--' text in your first index of ComboBox
                   dr = dTable.NewRow();
                   dr.ItemArray = new object[] { 0, "--Select--" };
                   dTable.Rows.InsertAt(dr, 0);

                   yourComboBox.DisplayMember = dTable.Columns["ProductName"].ToString();
                   yourComboBox.ValueMember = dTable.Columns["ID"].ToString();
                   yourComboBox.DataSource = dTable;
               }
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
           }


Always try to keep the connection string inside the configuration file (app.config).
And never concatenate strings to form an SQL command. you leave your code wide open to SQL Injection. Always use a parameterised query or stored procedure.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900