Search code examples
c#asp.net-mvcstored-proceduresdatasetado.net

Problem with dataset when table does not exist


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


Solution

  • 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 */;