Reputation: 1620
In my Project I am retrieving some details from the DB storing it in Dataset and checking it in IF condition, I had put the breakpoint in the IF condition line and executed it to check whether it was correctly running, the Condition is Failing (i.e there is no row in the Dataset I had seen in the Data Visualizer also) but it is moving in to the IF block and the Index Exception is Thrown What could be the Error in it,
My code is,
string mac = GetMac();
DataSet dr = Namespace.SP.Storedprocedure(mac).GetDataSet();
DataSet ds = Namespace.SP.Storedprocedure(mac).GetDataSet();
try
{
if (dr.Tables[0].Rows.Count > 0 || dr.Tables[0].Rows.Count <= 3)
{
string date = dr.Tables[0].Rows[0]["Date"].ToString();
if (Convert.ToInt32(dr.Tables[0].Rows[0]["CID"]) != Convert.ToInt32(Session["CollegeID"]))
{
Messaging("This System is already Registered Under Different College.");
getdet.Enabled = false;
Register1.Enabled = false;
}
else if (dr.Tables[0].Rows[0]["Mac_id"].ToString() == mac)
{
Messaging("This System has been Already Registered for Delivery on " + date);
getdet.Enabled = false;
Register1.Enabled = false;
}
}
else
{
Messaging("The Allowed Maximum Number of Systems has been Registered... ");
}
if (getdet.Enabled == false && Register1.Enabled == false && ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows[0]["Mac_id"] != mac)
{
getdet.Enabled = true;
Register1.Enabled = true;
}
}
ggvqpdetail.Visible = true;
fillgridQP();
foreach (GridViewRow gr in ggvdetail.Rows)
{
Anthem.Label lb = (Anthem.Label)gr.FindControl("lbl1");
lb.Text = "Downloading";
break;
}
}
catch(Exception ex)
{
lbltxt.Text = ex.Message;
}
Upvotes: 0
Views: 1080
Reputation: 216293
If the Rows.Count is zero this line is always true
if (dr.Tables[0].Rows.Count > 0 || dr.Tables[0].Rows.Count <= 3)
The OR
logical opertator gives false for the first condition, but true for the second so the whole expression is TRUE
.
Probably you need an AND
logical opertator
if (dr.Tables[0].Rows.Count > 0 && dr.Tables[0].Rows.Count <= 3)
but before this line you need to check for the rows count zero and take an appropriate action
if (dr.Tables[0].Rows.Count == 0)
{
// Operations for rows count == 0
}
else if(dr.Tables[0].Rows.Count <= 3)
{
// Operations for rows count <= 3
}
else
{
// limits reached.....
}
Upvotes: 4
Reputation: 1075
You should write
if (dr.Tables[0].Rows.Count > 0 || ((dr.Tables[0].Rows.Count <= 3) && (dr.Tables[0].Rows.Count >0)))
In your dr.Tables[0] may be no row is comming from database so you should validate it for row count.
Upvotes: 1
Reputation: 1526
your first if statement is doing the mistake,if you want the condition to be satisfied then you have to use AND
instead of OR so that after both conditions are satisfied then you can enter the inner code of if block
if (dr.Tables[0].Rows.Count > 0 && dr.Tables[0].Rows.Count <= 3)
Upvotes: 1