Home > database >  Problem with dataset when table does not exist
Problem with dataset when table does not exist

Time:08-11

I get an error when the wrong credential is entered but if I enter a true credential then I do not get an error.

See my login screen: if I enter true credential then I do not get any error

enter image description here

But if I enter the wrong credential then I get an error because the second table does not exist

enter image description here

The error is Cannot find table 1

enter image description here

HomeController.cs

[HttpPost]
public ActionResult ExecutiveLogin(int? exuserid, string exusername)
{
    SqlCommand cmd = new SqlCommand("executivelogin", cn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@executiveid", exuserid);
    cmd.Parameters.AddWithValue("@executivetypename", exusername);
    cn.Open();

    DataSet ds = new DataSet();

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    da.Fill(ds);

    ds.Tables[0].TableName = "Error Message";
    ds.Tables[1].TableName = "Customer Data";

    var message = ds.Tables[0].Rows[0].ItemArray[0];
    //object result = cmd.ExecuteScalar();

    List<Customer> query = null;
    if (ds.Tables[0].TableName == "Error Message")
    {
        ViewBag.errormessage = message;

        var Customerdata = (from DataRow row in ds.Tables[1].Rows
        select new Customer
        {
                    CustomerName = row["CustomerName"].ToString(),
                            Type = row["type"].ToString(),
        });
        query = Customerdata.ToList();

        ViewBag.custdata = query;
    }
    else
    {
        ViewBag.errormessage = message;
    }

    return View();

}

if I enter a true credential then not give an error and I enter the wrong credential then give an error

CodePudding user response:

If the user exists, you are executing two SELECT statements, so there are two DataTables in your DataSet. If the user doesn't exist, you're only executing one SELECT statement, so there's only one DataTable, so index 1 is out of range. You should be checking the contents of the first DataTable first, to see whether the login was successful, or else just check the number of DataTables first. Only if there is a second DataTable, should you try to get that second DataTable.

CodePudding user response:

Check for the count in dataset, then set name for second table.

ds.Tables.Count > 0 ? ds.Tables[1].TableName = "Customer Data" : /*No second datatable */;

  • Related