我希望将Windows窗体文本框中的输入与数据库中的字段进行比较。该表是'产品'而且这个领域是“ReOrderlevel'”。如果在文本框中输入的值小于ReOrderlevel,我需要一个消息框来显示“请立即订购”。我对C#完全不熟悉,并且不确定这些是否有意义,但我会在下面付出努力,万一有人能解决我的问题!非常感谢你!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
namespace rescue_centre
{
public partial class FrmStock : Form
{
public FrmStock()
{
InitializeComponent();
}
private void FrmStock_Load(object sender, EventArgs e)
{
refresh_data();
}
public void refresh_data()
{
string Query = "select * from stock";
MySqlConnection mycon = new MySqlConnection("datasource=localhost;username=root;password='';database=fsd;"); MySqlCommand cmd = new MySqlCommand(Query, mycon);
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlDataReader Mdr;
adapter.SelectCommand = cmd;
DataTable dTable1 = new DataTable();
adapter.Fill(dTable1);
DtgStock.DataSource = dTable1;
mycon.Open();
Query = "Select * from stock";
cmd = new MySqlCommand(Query, mycon);
Mdr = cmd.ExecuteReader();
CmbPrd.Items.Clear();
while (Mdr.Read())
{
CmbPrd.Items.Add(Mdr.GetString("ProdCode"));
}
mycon.Close();
mycon.Open();
Query = "Select * from stock";
cmd = new MySqlCommand(Query, mycon);
Mdr = cmd.ExecuteReader();
CmbLoc.Items.Clear();
while (Mdr.Read())
{
CmbLoc.Items.Add(Mdr.GetString("LocCode"));
}
mycon.Close();
}
private void QtyTxt_Validating(object sender, CancelEventArgs e)
{
string query = "Select ReOrderlevel from Product where (ProdCode)='" + CmbPrd.Text + "';";
MySqlConnection mycon = new MySqlConnection("datasource=localhost;username=root;password='';database=fsd");
MySqlCommand cmd = new MySqlCommand(query, mycon);
if
QtyTxt.Text<ReOrderLevel
MessageBox.Show("Stock Low Please Order Now")
mycon.Open();
cmd.ExecuteNonQuery();
mycon.Close();
refresh_data();
答案 0 :(得分:4)
您需要在if语句之前执行查询。 我将假设ReOrderlevel是一个整数,并且您的查询总是返回一行或更多行。
MySqlCommand cmd = new MySqlCommand(query, mycon);
int ReOrderLevel = Convert.ToInt32(cmd.ExecuteScalar());
if(Convert.ToInt32(QtyTxt.Text) < ReOrderLevel)
{
MessageBox.Show("Stock Low Please Order Now");
}
作为旁注,您不希望在Stock表中查询数据库3次。使用refresh_data
后的adapter.Fill(dTable1);
方法,你可以加载这样的组合框:
CmbPrd.Items.Clear();
CmbLoc.Items.Clear();
foreach (DataRow row in dTable1.Rows)
{
CmbPrd.Items.Add((string)row["ProdCode"]);
CmbLoc.Items.Add((string)row["LocCode"]);
}
请使用参数化查询以避免SQL注入。 代码示例
string query = "Select ReOrderlevel from Product where (ProdCode)= @prodcode;";
cmd.Parameters.AddWithValue("@prodcode", CmbPrd.Text);