So, I have a function which reads the result of a query that is used later on the program as it follows:
connection.Open();
int combination;
using (SqlCommand com1 = new SqlCommand())
{
com1.Connection = connection;
com1.CommandText = "select FinalComboId from relationTable where sourceCombo=@source and destinationCombo=@destination";
com1.Parameters.Add(new SqlParameter("@source",combo.ToString() ?? ""));
com1.Parameters.Add(new SqlParameter("@destination", destination ?? ""));
SqlDataReader comboLinkReader = com1.ExecuteReader();
if (!comboLinkReader.Read() || comboLinkReader.FieldCount==0)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"alertMessage", @"alert('Combination does not exists,please contact admin!')", true);
}
else
{
combination = Convert.ToInt32(comboLinkReader["FinalComboId"]);
}
}
What I would like to achieve is: if the result is empty, than execute the alert script, else save the result as an integer, that will be used for further calculations. I have followed several tutorials and examples regarding that issue, and when I executed the function the other day, it worked just fine. Now, 2 hours from launching it to production, it does not calculate the first condition:
if (!comboLinkReader.Read() || comboLinkReader.FieldCount==0)
{//calculations here}
I have also tried with
if (!comboLinkReader.Read() || comboLinkReader.IsDbNull(0))
{//calculations}
and I have the same problem. The query should return one single value. Is there something that I am doing wrong?
IsDbNullis a method that needs an argument for the column index.Readreturns true when you didn't expect it, what are the contents of the row it loaded? There's no reason to count fields or check for nulls (unless you have stored nulls in this field)