I'm having trouble displaying non-existent rows with if-else in a table with labels.
I'm currently logged in with this parentsID (logged in as New session) with two children (two rows) and there are no problems with dt.Rows[0] and dt.Rows[1] except I'm getting error at dt.Rows[2] with this Error: System.IndexOutOfRangeException: There is no row at position 2. As for the parentsID with three children, there's no error. Likewise, if I log in with a parentsID that has only one child then it displays There is no row at position 1.
How do I fix this? My english is not good, sorry if there are grammatical errors.
I have one table called family and it has everyone in it. All rows have childID(their username) along with parentsID. some child can be a parent of other childs.
try
{
string query = "select * from family where parentsID = '" + Session["New"] + "'";
using (OleDbCommand cmd3 = new OleDbCommand(query, con))
{
con.Open();
OleDbDataReader myReader3 = null;
myReader3 = cmd3.ExecuteReader();
if (myReader3.HasRows)
{
DataTable dt = new DataTable();
dt.Load(myReader3);
if (!DBNull.Value.Equals(dt.Rows[0]["childID"]))
{
label1.Text = dt.Rows[0]["childID"].ToString();
label2.Text = "$" + Convert.ToDecimal(dt.Rows[0]["childNetWorth"]).ToString("N2");
label3.Text = dt.Rows[0]["childName"].ToString();
}
else
{
label1.Text = "-ID-";
label2.Text = "-";
label3.Text = "-";
}
if (!DBNull.Value.Equals(dt.Rows[1]["childID"]))
{
label5.Text = dt.Rows[1]["childID"].ToString();
label6.Text = "$" + Convert.ToDecimal(dt.Rows[1]["childNetWorth"]).ToString("N2");
label7.Text = dt.Rows[1]["childName"].ToString();
}
else
{
label5.Text = "-ID-";
label6.Text = "-";
label7.Text = "-";
}
if (!DBNull.Value.Equals(dt.Rows[2]["childID"]))
{
label9.Text = dt.Rows[2]["childID"].ToString();
label10.Text = "$" + Convert.ToDecimal(dt.Rows[2]["childNetWorth"]).ToString("N2");
label11.Text = dt.Rows[2]["childName"].ToString();
}
else
{
label9.Text = "-ID-";
label10.Text = "-";
label11.Text = "-";
}
}
}
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
finally
{
con.Close();
}