我想获得组合框中所选值的id

时间:2015-07-31 17:58:40

标签: c#

我的ComboBox的值来自sql数据库,它的工作效果很好,但是我希望获得该值的Med_id以便我添加另一个条目

Med_ID是来自另一个表的外键,有没有办法获取它并将其添加到y分类帐表?

这是代码:

string MyConnection2 = "datasource=localhost;port=3306;user id=root;password=''";
string Query = "INSERT INTO
                newssph.ledger(Date, Reference, Rec_Qty, Iss_Qty, Bal_Qty, Med_ID)
                VALUES('" + txtdate.Text + "','" + comboBox4.Text + "','"
                          + this.txtrec.Text + "','" + this.txtissue.Text +
                          "','" + this.txtbal.Text + "','" + id + "','" +
                      "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MessageBox.Show("Data Added");

1 个答案:

答案 0 :(得分:0)

您发布的代码存在很多问题。你似乎在使用不正确的控件。文本框不是日期或数字的好选择。如果可能的话,我建议给你的数据库列更好的名字。什么是约会?这是输入,编辑,到期,过期的日期吗?只需几个字符就可以增加很多清晰度。如果这是我的代码,我会将此插入移动到存储过程,但这是如何将此代码转换为sql注入安全的东西。

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConfigKeyHere"].ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "insert into newssph.ledger(Date, Reference, Rec_Qty, Iss_Qty, Bal_Qty, Med_ID) values(@Date, @Reference, @Rec_Qty, @Iss_Qty, @Bal_Qty, @Med_ID)";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = txtdate.Text; //Why are you using a textbox instead of a datepicker???
                    cmd.Parameters.Add("@Reference", SqlDbType.VarChar, 25).Value = comboBox4.Text; //Seriously??? comboBox4??? Give your controls names
                    cmd.Parameters.Add("@Rec_Qty", SqlDbType.Int).Value = this.txtrec.Text; //Why are you again using text? this should be a control that only allows numbers
                    cmd.Parameters.Add("@Iss_Qty", SqlDbType.Int).Value = this.txtissue.Text;
                    cmd.Parameters.Add("@Bal_Qty", SqlDbType.Int).Value = this.txtbal.Text;
                    cmd.Parameters.Add("@Med_ID", SqlDbType.Int).Value = this.comboBox4.Value;
                    cmd.ExecuteNonQuery();
                }
            }