c# - C# SQL Server 从数据库中读取数量并将其显示在消息框中
问题描述
所以我几乎完成了使用 C# 和 sql server management studio 完成我的 POS,但是我在显示特定产品的可用数量时遇到问题,如果你输入的 Quantity 大于 Stocks(每种产品的数量是基于我的股票)并点击添加按钮,将出现一个消息框,提示用户该产品的唯一可用数量就是这样。
这是为了确定数量是否超过:
public void Q_tity()
{
try
{
SqlConnection cn = new SqlConnection();
con.Open();
string qwe = "Select MIN(Quantity/Quantifier) from Stocks where ItemID in (Select ItemID from Recipe where MenuID in (Select MenuID from Menu where ItemName ='" + txtProd.Text + "'))";
SqlCommand cmd = new SqlCommand(qwe, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
if (txtProd.Text == "")
{
MessageBox.Show("Please Input a correct format", "Format info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
double val = double.Parse(dr[0].ToString());
Quantity = Convert.ToInt32(val);
}
}
}
catch
{
MessageBox.Show("The ingredient on recipe cannot identify. please fix it from the maintenance form", "Recipe Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
}
这是应该提示用户的添加按钮:
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtQuant.Text.Length == 0)
{
MessageBox.Show("Quantity Field is Required!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Q_tity();
con.Open();
// con.Close();
if (Quantity < Convert.ToDouble(txtQuant.Text))
{
string qwe = "Select MIN(Quantity/Quantifier) from Stocks where ItemID in (Select ItemID from Recipe where MenuID in (Select MenuID from Menu where ItemName ='" + txtProd.Text + "'))";
SqlCommand cmd = new SqlCommand(qwe, con);
SqlDataReader dr = cmd.ExecuteReader();
MessageBox.Show(txtQuant.Text + " is unavailable! \n The Available Quantity of " + txtProd.Text + " is " + dr + " only!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
con.Close();
}
可悲的是,这就是结果:
解决方案
在您的情况下,您必须使用 ExecuteScalar() 而不是 ExecuteReader
这是修复
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtQuant.Text.Length == 0)
{
MessageBox.Show("Quantity Field is Required!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Q_tity();
con.Open();
// con.Close();
if (Quantity < Convert.ToDouble(txtQuant.Text))
{
string qwe = "Select MIN(Quantity/Quantifier) from Stocks where ItemID in (Select ItemID from Recipe where MenuID in (Select MenuID from Menu where ItemName ='" + txtProd.Text + "'))";
SqlCommand cmd = new SqlCommand(qwe, con);
int qty = Convert.ToInt32(cmd.ExecuteScalar()); //<-- use executescalar
MessageBox.Show(txtQuant.Text + " is unavailable! \n The Available Quantity of " + txtProd.Text + " is " + qty + " only!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
con.Close();
}
}
推荐阅读
- php - .htaccess 重写 url 参数和键
- c - C:使用指针计算数组总和的函数
- android - 已解决:制作主屏幕快捷方式时,默认的 Androd 图标是什么?
- node.js - Firestore 创建后获取文档
- python - input() 接受 2 个位置参数,但给出了 3 个
- oracle - 如何在 PL/SQL 游标中给出参数
- angular - 来自 API 的 Angular 接收文件
- qt - 如何在 QML RangeSlider 对象上显示刻度?
- javascript - javascript match() 不带斜线
- git - 使用 Eclipse 将项目附加到 git 存储库