当值低于-时显示MessageBox

本文关键字:显示 MessageBox -时 | 更新日期: 2023-09-27 17:51:15

基本上,我想要一个消息框,出现当我的表单是说,该值低于一个常量值(如30)加载。这是我刚刚写的代码,但它不工作,因为IF条件在语法上不正确。

private void button2_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|DataMG.mdb";
        System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.CommandText = "Select COUNT(*) from Prodotti where Disponibilta < 30";
        cmd.Connection = conn;
        conn.Open();
        var count = (int)cmd.ExecuteScalar();
        if (count < 0)
        {
            MessageBox.Show("Attenzione alcuni prodotti sono in disponibilita' limitata!");
            conn.Close();
        }
    }

我该怎么办?由于

当值低于-时显示MessageBox

试试这样:

using (var cmd = new OleDbCommand())
{
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select COUNT(*) from Prodotti where Disponibilta < 30";
    var count = (int)cmd.ExecuteScalar();
    if (count > 0)
    {
        MessageBox.Show("Attenzione alcuni prodotti sono in disponibilita' limitata!");
        //connection.Close(); wrap connection around an using
    }
}

基本上,你要求建立数据库的Prodotti的数量,可处置性<</p>

编辑

我假设Disponibilta是一个数字

您不应该使用ExecuteNonQuery()与简单的SELECT语句,SQLDataReader是更快和正确的方式来做到这一点:

cmd.CommandText = "SELECT * FROM Prodotti WHERE Disponibilta < 30";
conn.Open();
MySqlDataReader myReader = cmd.ExecuteReader();
if(myReader.HasRows)
{
    //This means you have at least one product with less than 30.
}
myReader.Close();
conn.Close();

Select关键字引入了查询,因此必须使用.ExecuteReader().ExecuteNonQuery()用于INSERTDELETEUPDATE,返回值为受影响的行数。

根据您的情况,创建一个阅读器并检查第一个值

OleDbDataReader reader = command.ExecuteReader();
while (reader.Read() 
{ 
    if (reader[0] < aValue) //make here the appropiate conversion
    {
        MessageBox.Show("Attenzione alcuni prodotti sono in disponibilita' limitata!");
        connection.Close();
        break;//maybe return?
    }
}