【问题标题】:From Combobox to textbox error message从组合框到文本框错误消息
【发布时间】:2017-09-22 08:39:33
【问题描述】:
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
            string Query = "SELECT Barcodes, Name, EDate, Quantity, Price FROM Products where Name='" + cbxProducts.Text + "' ; ";
            SqlConnection conDataBase = new SqlConnection(constring);
            SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
            SqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDataBase.ExecuteReader();


                    string sBarcode = myReader["Barcodes"].ToString();
                    string sName = myReader["Name"].ToString();
                    var sDate = myReader["EDate"];
                    string sQuantity = myReader["Quantity"].ToString();
                    string sPrice = myReader["Price"].ToString();
                    tbxBar.Text = sBarcode;
                    tbxName.Text = sName;
                    sDate = dateDate.Value;
                    tbxPrice.Text = sPrice;
                    tbxQua.Text = sQuantity;


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

当我尝试使用此代码时,我只会收到错误消息 “当没有数据可用时进行了无效的读取尝试”我的数据库中确实有数据,但它仍然无法正常工作。

【问题讨论】:

标签: c# sql combobox textbox


【解决方案1】:

Reader 对象逐行获取行,我们需要使用Read() 方法告诉它带入下一行。

您需要调用SqlDataReader 对象的Read() 方法来读取每一行,如果预期有单行,那么您可以通过if 进行操作,否则您必须在while 循环中进行,例如:

while(myReader.Read())
{

                string sBarcode = myReader["Barcodes"].ToString();
                string sName = myReader["Name"].ToString();
                var sDate = myReader["EDate"];
                string sQuantity = myReader["Quantity"].ToString();
                string sPrice = myReader["Price"].ToString();
                tbxBar.Text = sBarcode;
                tbxName.Text = sName;
                sDate = dateDate.Value;
                tbxPrice.Text = sPrice;
                tbxQua.Text = sQuantity;
}

另一件事是您在创建查询时不应该进行字符串连接,请考虑使用参数化查询,因为您的代码对SQL Injection 开放。您可以阅读How to: Execute a Parameterized Query 了解如何编写参数化查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    相关资源
    最近更新 更多