Problem with dataset when table does not exist - c#

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
But if I enter the wrong credential then I get an error because the second table does not exist
The error is Cannot find table 1
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

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.

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

Assign DataSet to Local Variables

I am running a SQL Query and returning a DataSet - I want to iterate the info in the DataSet and assign the values to local variables. I have confirmed that my DataSet returns rows but my variables are not getting assigned for some reason. Can someone look at my syntax and assist with why this is occurring?
protected void GetSomeData()
{
string employeeid = this.txtemployeeid.Text;
DataSet empinfo = new DataSet();
empinfo = RunSqlQuery(employeeid);
this.txtemployeefirstname = empinfo.Tables[0].Rows[0]["employeefirstname"].ToString());
this.txtemployeelastname = empinfo.Tables[0].Rows[1]["employeelastname"].ToString());
this.txtemployeeaddress = empinfo.Tables[0].Rows[2]["employeeaddress"].ToString());
this.txt.employeephone = empinfo.Tables[0].Rows[3]["employeephone"].ToString());
}
public DataSet RunSqlQuery(string employeeid)
{
string sqlQuery = "Select employeefirstname, employeelastname, employeeaddress, employeephone from abcd where employeeid = "+employeeid+" and employeeid is not null";
try
{
connectionString = System.Configuration.ConfigurationManager.AppSettings[connectionString].ToString();
sqlDatabaseConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand(sqlQuery, sqlDatabaseConnection);
sqlDatabaseConnection.Open();
sqlCommand.CommandTimeout = 0;
dataSet = new DataSet();
sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataSet, "Data");
return dataSet;
}
catch (Exception exception)
{
throw exception;
}
finally
{
sqlDatabaseConnection.Close();
sqlCommand.Dispose();
sqlDataAdapter.Dispose();
}
}
EDIT
By variables not getting assigned, I mean when I step through my code, it seems that the value returned from the database is not being populated into the empinfo.Tables[0].Rows[0]["employeefirstname"].ToString()); they are always null.
You're assigning the value to the textbox (at least, I assume txtemployeefirstname is a textbox). I think you mean txtemployeefirstname.text?

Select datatable with join return 0

I have one DataTable that executes this SQL query on my MS Access database in C#:
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT tblCdDvd.Cod, tblCdDvd.Nome, tblCdDvd.Tamanho, tblTipo.Tipo, tblCdDvd.Grupo FROM [tblCdDvd] INNER JOIN [tblTipo] ON tblCdDvd.Tipo=tblTipo.Cod WHERE Status = TRUE");
If I use
DataRow[] result = dtCdDvd.Select("[Grupo]=0");
the result is 0 rows and exist registry with informed code.
The more interesting is if my SQL query runs
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT Grupo FROM tblCdDvd");
without join table my result is different of 0.
My function of return datatable
public DataTable Fun_RetornaDataTable(string query)
{
DataTable dt = null;
using (var dbcon = new OleDbConnection(Fun_ConnString()))
{
dbcon.Open();
if (dbcon.State == ConnectionState.Open)
{
var command = new OleDbCommand(query, dbcon);
dt = new DataTable();
dt.Load(command.ExecuteReader());
}
}
return dt;
}
Very difficult to understand the question, but a couple of things that stand out.
" WHERE Status = TRUE"
What is 'Status'? Is it defined in one of the tables uniquely?
When you run "SELECT Grupo FROM tblCdDvd", are you getting any rows returned?
"the result is 0 rows and exist registry with informed code"
What does this mean in English?

Cannot find table 0 in dataset using stored procedures

I am not getting filled dataset after executing a stored procedure.
protected void btnsub_Click(object sender, EventArgs e)
{
ArrayList arInsert = ReturnParameter_insert();
DataSet dsInsertProfile = objadmin.GetGridData(arInsert, objconstant.sSP_INSERT_PROFILE);
if(int.Parse(dsInsertProfile.Tables[0].Rows[0].ItemArray[0].ToString())== 0)
{
lblThank.Text = "Your profile have been successfully saved.";
}
else
{
lblThank.Text = "Your profile is not saved, please try again later.";
}
}
public ArrayList ReturnParameter_insert()
{
ArrayList arProfile = new ArrayList();
Object[] c_first_name = new object[3] { "#strFname", "Varchar", (txtfname.Text != "") ? txtfname.Text : "" };
arProfile.Add(c_first_name);
return arProfile;
}
public DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
dsDataSet = datamanager.GetGridData(dbArray, sSpName);
return dsDataSet;
}
public static SqlDbType GetSqlDataType(string sDataType)
{
return (sDataType == "Integer") ? SqlDbType.Int : (sDataType == "Varchar") ? SqlDbType.VarChar : (sDataType == "Date") ? SqlDbType.Date : SqlDbType.BigInt;
}
public static DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
SqlConnection cn = createConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sSpName;
object objPrMtrName;
object objSqlType;
object objPrMtrVal;
int i;
for (i = 0; i < dbArray.Count; i++)
{
objPrMtrName = ((object[])(dbArray[i]))[0];
objSqlType = ((object[])(dbArray[i]))[1];
objPrMtrVal = ((object[])(dbArray[i]))[2];
cmd.Parameters.Add(objPrMtrName.ToString(), GetSqlDataType(objSqlType.ToString())).Value = objPrMtrVal;
}
cmd.Connection = cn;
try
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
return dsDataSet;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
cn.Dispose();
}
}
My stored procedure:
CREATE Procedure spInsert_profile
(#strFname varchar(200))
AS
BEGIN
INSERT INTO gdt_Users([c_first_name], [d_modified_dttm], [d_created_dttm])
VALUES(#strFname, GETDATE(), GETDATE())
END
Here I am using 3 tier, the same methods are working successfully for other pages but not for this particular code. The dataset in GETGRIDDATA method is filling null value. I am not able to find. Please help me....
you performing insert operation in your procedure than how is going to return to data Insert into statement does insert operation not retrieve operation.
...To retrieve data you need to call procedure with select * statement.
There is no select statement in your stored proc. adapter.fill() should recieve some sort of table from the stored proc's output.
From what I can see here you are executing a stored procedure that only performs an INSERT command, The reason you are getting a NULL value back is because a non query command such as UPDATE or INSERT will generally return only the number of rows affected e.g. 1 and not the data of the table you inserted to.
You would need to perform a SELECT command after the insert to get any data back.
The problem is in your stored procedure... you have to add select statement to the stored procedure for your return result in DataSet
Because you use Insert Into in your stored procedure.
Access based on Tables property:
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
var table1 = dsDataSet.Tables[0];
var table2 = dsDataSet.Tables[1];
Link : http://msdn.microsoft.com/fr-fr/library/system.data.dataset.tables.aspx

Get profile id using username in DB

I have to catch the username entered in the login page and get corresponding profileid(the column in DB) and show it in another page my DAL code is
public DataTable getall()
{
SqlConnection conn1 = Generic.DBConnection.OpenConnection();
DataTable dt=new DataTable();
try
{
string sql = "Select * from Profile_Master";
SqlCommand cmds = new SqlCommand(sql,conn1);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmds);
sqlDa.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
My UI
DataTable dt1 = new DataTable();
ProfileMasterDAL dal = new ProfileMasterDAL();
dt1 = dal.getall();
if (dt1.Rows.Count > 0)
{
Session["sdds"] = dt1.Rows[0]["FirstName"].ToString();
Session["EmailId"] = dt1.Rows[0]["EmailID"].ToString();
Session["pid"] = dt1.Rows[0]["NewidColumn"].ToString();
Response.Redirect("~/Myhome.aspx");
but i am able to get the first value in the DB not the corresponding value for the username?
Your select statement has 10 rows. and the required row for you is in 5th position.
when you say dt1.Rows[0]["FirstName"] you will get only the first record but not the 5th record.
If you want to make this work, add where condition to your select statement, which returns exactly one required row for you.
something like..
"select * from Profile_Master PM Where PM.UserName = #username"
where #username is your input from login page. And is unique in the database Table

check if primary key exist

I have tried posting this earlier and had to delete it because the code editor did not post it correctly and incompletely. plus I had a member ask me about SQL injection.
Here's the story:
I have a page where the user can check his information before it is submitted to the database. All I want to do is look to see if that primary key is present before I submit it to avoid getting a server error.
In my page load event I have the following:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
SqlCommand oldcmd = new SqlCommand("SELECT * from dbo.registrar WHERE [MY ID] = '"+ID+"'", conn);
oldcmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(oldcmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count >= 1)
{
lblExists.Visible = true;
lblExists.ForeColor = System.Drawing.Color.Red;
lblExists.Text = "Oops! Our records show that you have already signed up for this service. Please check your information or contact your administrator for further assistance.";
}
The label fires even though there is no record in the database which tells me that I am doing it wrong.
Try this.
SqlCommand oldcmd = new SqlCommand("SELECT COUNT(*) from dbo.registrar WHERE [MY ID] = #id", conn);
oldcmd.Parameters.Add("#id", SqlDbType.Int);
oldcmd.Parameters["#id"].Value = ID;
if ((int)oldcms.ExecuteScalar() >= 1)
{
lblExists.Visible = true;
lblExists.ForeColor = System.Drawing.Color.Red;
lblExists.Text = "Oops! Our records show that you have already signed up for this service. Please check your information or contact your administrator for further assistance.";
}
else
{
lblExists.Visible = false;
}

Categories