C# 从组合框到文本框错误消息
当我尝试使用此代码时,我只收到错误消息C# 从组合框到文本框错误消息,c#,sql,combobox,textbox,C#,Sql,Combobox,Textbox,当我尝试使用此代码时,我只收到错误消息 “在没有可用数据的情况下进行了无效的读取尝试”我的数据库中确实有数据,但它仍然不工作。Reader对象逐个获取行,我们需要告诉它使用read()方法获取下一行 您需要调用SqlDataReader对象的Read()方法来读取每一行,如果需要一行,那么您可以通过if执行,或者您必须在中执行,而循环类似于: private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
“在没有可用数据的情况下进行了无效的读取尝试”我的数据库中确实有数据,但它仍然不工作。
Reader
对象逐个获取行,我们需要告诉它使用read()
方法获取下一行
您需要调用SqlDataReader
对象的Read()
方法来读取每一行,如果需要一行,那么您可以通过if
执行,或者您必须在中执行,而循环类似于:
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);
}
}
另外一个问题是,在创建查询时,不应该做字符串连接,请考虑在代码打开时使用参数化查询。您可以阅读了解如何编写参数化查询。
Reader
对象逐个获取行,我们需要告诉它使用read()
方法获取下一行
您需要调用SqlDataReader
对象的Read()
方法来读取每一行,如果需要一行,那么您可以通过if
执行,或者您必须在中执行,而循环类似于:
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);
}
}
另外一个问题是,在创建查询时,不应该做字符串连接,请考虑在代码打开时使用参数化查询。您可以在了解如何编写参数化查询时阅读。
重复问题…到底哪一行抛出错误?调试时,myReader
的值是多少?myReader
不应该是一个值列表吗?重复问题的可能重复…到底哪一行抛出错误?调试时,myReader
的值是多少?myReader
不应该是一个值列表吗?可能是