我有一个名为Combobox2的组合框,我想用一个名为``bulkinput''的表的列内容填充该组合框.有任何想法吗? [英] I have a combobox which is called combobox2, which I want to populate with the content of the column of a table called "bulkinput". Any ideas?

查看:133
本文介绍了我有一个名为Combobox2的组合框,我想用一个名为``bulkinput''的表的列内容填充该组合框.有任何想法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够将表​​字段(列)的内容复制到组合框中,以便用户可以直接从那里进行选择,而无需在设计期间输入组合框的值.

我尝试过的事情:

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);
            }
        } 

推荐答案

对于初学者,请不要那样做!切勿串联字符串以构建SQL命令.它使您对意外或蓄意的SQL注入攻击敞开大门,这可能会破坏整个数据库.请改用参数化查询.

其次,在尝试使用阅读器之前,需要打开连接.

第三,不要使用DataReader-它们在运行时需要所有内容,并且在加载组合框之前,您的连接已关闭.请改用DataAdapter和DataTable:
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);
    }



始终尝试将连接字符串保留在配置文件中(app.config或web.config,在您的情况下为app.config).说,如果配置文件中的键名为"conn",则可以按如下所示获取值



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();


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.


这篇关于我有一个名为Combobox2的组合框,我想用一个名为``bulkinput''的表的列内容填充该组合框.有任何想法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆