Showing MessageBox when value is lower than - - c#

Basically I want a MessageBox that appears when my Form is loaded that is saying that the value is lower than a constant value ( like 30 ).
This is the code I just wrote but its not working since the IF condition is not syntactly correct.
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();
}
}
What should I do ?
Thanks

Try something like this:
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
}
}
Basically you ask to database the number of Prodotti that Disponibilta < 30, so if any you show the messagebox.
EDIT
I assume that Disponibilta is a numeric.

You shouldn't use ExecuteNonQuery() with a simple SELECT statement, SQLDataReader is quicker and the proper way to do this:
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 keyword introduces a query, so you have to use .ExecuteReader()..ExecuteNonQuery() is used for INSERT, DELETE, UPDATE and return value is the number of rows affected.
For your situation, create a reader and check the first value
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?
}
}

Related

The parameterized query expects parameter xy which was not supplied

I'm trying to do an app without adding some details about a car delivery.
I wrote the code in C# and SQL, but when I add the data to textbox, radiobutton, labels, etc. I get this error:
System.Data.SqlClient.SqlException: 'The parameterized query '(#a int,#b nvarchar(7),#c int,#d nvarchar(12),#e nvarchar(10),#f' expects the parameter '#f', which was not supplied.'
But I tried by debug to see if they take values and all have values less #f
The length of the columns in the database is 50 or 100
if (materialRadioButton5.Checked)
{
choose = "Excelent";
}
else if (materialRadioButton8.Checked)
{
choose = "Foarte bună";
}
else if (materialRadioButton7.Checked)
{
choose = "Bună";
}
else if (materialRadioButton6.Checked)
{
choose = "Uzată";
}
if (materialRadioButton4.Checked)
{
chooser = "Mulţumit";
}
else if (materialRadioButton1.Checked)
{
chooser = "Nemulţumit";
}
SqlConnection con = new SqlConnection(stringcon);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.Parameters.Clear();
cmd.CommandText = "insert into returncar(id_client,fullname_client,id_team,fullname_team,rendition,condition,team_mention,customers_plesed,exp_felt,client_mention) values(#a,#b,#c,#d,#e,#f,#g,#h,#i,#j)";
cmd.Parameters.AddWithValue("#a", Convert.ToInt32(label65.Text));
cmd.Parameters.AddWithValue("#b", label67.Text);
cmd.Parameters.AddWithValue("#c", Convert.ToInt32(label66.Text));
cmd.Parameters.AddWithValue("#d", label68.Text);
cmd.Parameters.AddWithValue("#e", metroDateTime1.Text);
cmd.Parameters.AddWithValue("#f", choose);
cmd.Parameters.AddWithValue("#g", firstname_textbox.Text);
cmd.Parameters.AddWithValue("#h", chooser);
cmd.Parameters.AddWithValue("#i", role_dropbox.selectedValue);
cmd.Parameters.AddWithValue("#j", materialSingleLineTextField1.Text);
cmd.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = con;
cmd2.Parameters.Clear();
cmd2.CommandText = "update rentcar set inchiriat=0 where id=#id";
cmd2.Parameters.AddWithValue("#id", Form2.idddloan);
cmd2.ExecuteNonQuery();
con.Close();
panel2.Visible = false;
bunifuFlatButton7.Visible = false;
How radiobutton4 and radiobutton1 works and the others do not?...
public string choose, chooser;
If the value is null then the parameter is not added and you'll get the exception you mentioned. In these cases make sure to check for null and instead pass
choose ?? Value.DBNull

if (counter == < database value >)

How do I make the value from my database as a int that I can use for my if else function ?
For example: In my database "armnumber = 3", how do I use it in my if else function ?
code
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
try
{
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
string sqlStr = "Select armnumber from assign where id=1";
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
}
#endregion
if (counter == )
{
}
One option would be MySqlDataAdapter like this:
MySqlDataAdapter da = new MySqlDataAdapter {SelectCommand = cmd};
DataSet ds = new DataSet();
int armnumber = da.Fill(ds);
...
if (counter == armnumber)
Also you should always use parameterized queries to avoid SQL Injection:
string sqlStr = "Select armnumber from assign where id=#id";
cmd.Parameters.AddWithValue("#id", 1);
//Or better
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
You should replace this code
connection.Open();
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int databaseValue = int.Parse(reader["armnumber"].ToString());
connection.Close();
Few initial notes:
Continue operations after getting exception will not be a good practice, so I prefer the condition if (counter == xx ) inside the try block.
If the value of ID in the where clause is variable then make use of parameterization instead for concatenated queries.
Since you are fetching only a single field make use of ExecuteScalar instead for ExecuteNonQuery
You can make use of using als well for proper managing of connection and command objects.
So the code can be written as :
try
{
string sqlStr = "Select armnumber from assign where id=#id";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Parameters.AddWithValue("#id", 1);
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
var result = cmd.ExecuteScalar();
int armnumber = result != null ? int.Parse(result.ToString()) : 0;
if (counter == armnumber)
{
// code here
}
}
catch (MySqlException ex)
{
}

C# SQL Add parameter

I tried to return a row by executing following SQL query in C#:
SqlCommand cmd = new SqlCommand();
string selectquery = "SELECT TOP (1) [ZVNr] ZVNR_TABLE WHERE [ZVNr] = #zvnr order by [ZVNr] DESC";
cmd.Parameters.AddWithValue("#zvnr", "20170530-01");
cmd.CommandText = selectquery;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
try
{
sqlConnection.Open();
int recordsAffected = cmd.ExecuteNonQuery();
if(recordsAffected != -1)
{
return 0;
}
else
{
return 1;
}
And the "ZVNR_TABLE" looks like this:
ZVNR | varchar (50)
20170530-01
The result is always --> recordsAffected = -1
Although when I'm executing the same SQL query in Microsoft SQL Server Management Studio, it works.
You're using a SELECT statement in your code with cmd.ExecuteNonQuery which is used for INSERT or UPDATE statements.
You have to use a SQLDataReader (more than 1 row and(!) column) or Scalar (1 row/1col = one "item").
MSDN Example for SQLDataReader:
//SELECT col1, col2, ..., coln FROM tbl;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
MSDN Example for ExecuteScalar:
//SELECT COUNT(*) FROM region; or any other single value SELECT statement
int count = (int)cmd.ExecuteScalar(); //cast the type as needed
If you want the affected count after you change items in your database, you can get it by using cmd.ExecuteNonQuery which returns that count:
MSDN Example for ExecuteNonQuery:
//INSERT INTO tbl (...) VALUES (...) or any other non-query statement
int rowsAffected = (Int32)cmd.ExecuteNonQuery();
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command.
Because you are Selecting the data from the datatable not inserting or updating the records that's why recordsAffected is always -1
Answers given above are ok but if you want just to see if it exist you can do a count instead
using (SqlConnection connection = new SqlConnection(connectionstring))
{
string query = "SELECT Count([ZVNr]) ZVNR_TABLE WHERE [ZVNr] = #zvnr order by [ZVNr] DESC";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#zvnr", "20170530-01");
try
{
connection.Open();
int result = (int)cmd.ExecuteScalar();
}
}
}
ExecuteNonQuery() is used for INSERT or UPDATE statements and returns the number of rows affected.
If you want to return a single field of a row, you have to use ExecuteScalar()
using (SqlConnection connection = new SqlConnection(connectionstring))
{
string query = "SELECT TOP (1) [ZVNr] ZVNR_TABLE WHERE [ZVNr] = #zvnr order by [ZVNr] DESC";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#zvnr", "20170530-01");
connection.Open();
object result = cmd.ExecuteScalar();
}
}

Integer is being returned as 0 when it shouldn't be. Retrieved from database

I'm trying to get a value from my database but it keeps returning a value of 0 and i cannot figure out why. I've been retrieving data from the database for the whole of my project and it is just not working here. None of the values in the database are = to 0.
int rentalPrice is the one being returned as 0`
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("DisplayCars.aspx");
}
else
{
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cars where id ='" + id + "'";
cmd.ExecuteNonQuery();
lblCarID.Text = id.ToString();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
foreach (DataRow dr2 in dt2.Rows)
{
rentalPrice = Convert.ToInt32(dr2["car_rental_price"]);
}
lblRentalPrice.Text = rentalPrice.ToString();
con.Close();
}
// This uses a Connection pool, so you don't need to reuse the same SqlConnection
using (SqlConnection con = new SqlConnection(...))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select [car_rental_price] from cars where id = #Id";
var idParam = new SqlParameter("#Id");
idParam.Value = id;
cmd.Parameters.Add(idParam);
con.Open();
using (var reader = cmd.ExcecuteReader())
{
reader.Read();
lblRentalPrice.Text = reader.GetInt32(0).ToString();
lblCarID.Text = id.ToString();}
}
}
}
To execute a query and get results, you need to use cmd.ExecuteReader.
Also, rather than concatenating values into a string to build your SQL query, you need to use parameterized queries. This helps prevent SQL Injection attacks.
Also, SqlConnection should not be put in a field (class level variable). Instead, you should use local variables and wrap them in a using statement to ensure that they get disposed of properly.
hey you did not fill the Data Table.. then how it has any Values???
first Fill the data Table and use it in Foreach loop
adapter.Fill(DataTable);
foreach(DataRow dr in DataTable)
{
//get the id
}

SQL command not executing as expected

What is wrong with this code? I want to catch the last value from SQL row and display it in a TextBox. Kindly help me.
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select last(remain) from item_new_customer where cust=" + textBox2.Text + "";
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
cmd.CommandText = "select max(remain) from item_new_customer where cust='" + textBox2.Text + "'";
You are open for SQL-Injection, use parameters to avoid it.
To answer your actual question, i assume that you want this column: remain. But you want the value of the last inserted record. Since you haven't mentioned the column to detect the order of insertion, i use the primary key column (not recommended):
string sql = "SELECT TOP 1 remain FROM dbo.tablename WHERE cust=#cust ORDER BY id DESC";
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#cust", textBox2.Text);
con.Open();
double h = (double)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
You're missing a single quote after the textBox2.Text:
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"select max(remain) from item_new_customer where cust=" + textBox2.Text + "'";
//Missing tick here ^
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
In addition, your code is an open invitation for SQL injection.
Thanks very much for all
My final right code is:
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select top 1(remain) from item_new_customer where cust='"+textBox2.Text+"' order by id desc";
int h = (int)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
What I would just do is put all of the SQL row values into a listbox and then take the text of the last item in the textbox and put that into a textbox. Keep the listbox hidden
private System.Windows.Forms.ListBox listBox1;
static SqlConnection connection = new SqlConnection(#"Data Source=hostname;Initial Catalog=database_name;Integrated Security=False;User ID=user;Password=123456;");
SqlDataAdapter adapter = new SqlDataAdapter("select * from table_name", connection);
DataTable table = new DataTable();
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
listBox1.Items.Add(row["row_name"].ToString());
}
textBox20.Text = listBox1.Items[listBox1.Items.Count - 1].ToString();

Categories