In my code when I debug using Visual Studio C# I noticed that although there are no rows in the query :
select MAX(idSalesJournal) as maxId from accountingsystemdb.salesjournal"
the dr.HasRows property always returns TRUE. When I continue debugging I noticed that the loop will run for 1 time before exiting from the loop. Now I have a big problem because although there are no data in the dataset how the loop will run 1 time. Then I printed the value I get in a messagebox and it shows nothing (blank). How could this happen and how can I avoid this thing ? I will put an image of the same query that I have executed in the mySql workbench which executed successfully and didn't show any rows in the result. It shows 0 rows in MySql. Same query executed in C# will return Hasrows property as True. I have put my complete code in below.
public void salesJournal(string addOrRemove, string lorryNo, string invoiceNo, DateTime billDate, string source, DateTime paybackDate, string itemCode, double itemcost, string desc, double qty, double discount, double amount, string debtor)
{
if (conn.State.ToString() == "Open")
{
conn.Close();
conn.Open();
}
int maxID = 0;
if (conn.State.ToString() == "Closed")
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
//---------------------- Selecting Max ID ------------------------------------------
cmd.CommandText = "select MAX(idSalesJournal) as maxId from accountingsystemdb.salesjournal";
try
{
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows && dr != null)
{
while (dr.Read())
{
maxID = Convert.ToInt32(dr["maxId"].ToString());
}
}
else
{
maxID = 0;
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
conn.Close();
//---------------------------------------------------------------------------------
if (conn.State.ToString() == "Open")
{
conn.Close();
conn.Open();
}
else
{
conn.Open();
}
try
{
cmd.CommandText = "insert into accountingsystemdb.salesjournal VALUES('" + maxID + 1 + "', STR_TO_DATE('" + billDate + "', '%m/%d/%Y %h:%i:%s %p'), '" + invoiceNo + "', '" + lorryNo + "', '" + source + "', '" + itemCode + "', '" + desc + "', '" + qty + "', '" + itemcost + "', '" + amount + "', '" + discount + "', '" + addOrRemove + "', STR_TO_DATE('" + paybackDate + "', '%m/%d/%Y %h:%i:%s %p'), '" + debtor + "', '" + Program.username + "')";
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
conn.Close();
}
}