sql data reader class - asp.net

I did sql command with SqlDataReader but I had this error
System.IndexOutOfRangeException: UserName
Page Load event:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("Total", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataReader Dr = Com.ExecuteReader();
if (Dr.Read())
{
string Result= Dr["UserName"].ToString();
Lbltotal.Text = Result;
}
}
}
Stored Procedure:
Alter proc Total
as
begin
select Count (UserName) from Registration
end

Change your storder procedure to:
Alter proc Total
as
begin
select Count (UserName) as UserName from Registration
end

You're not returning any column called UserName - you're just returning a count which has no explicit column name.
If you have something like this - just a single value - you could also use the ExecuteScalar method which will return exactly one value:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
int count = (int)Com.ExecuteScalar();
}
If you insist on using the SqlDataReader, you just need to use a positional parameter:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
using(SqlDataReader Dr = Com.ExecuteReader())
{
if (Dr.Read())
{
string Result= Dr[0].ToString(); // take value no. 0 - the first one
Lbltotal.Text = Result;
}
}
}

Related

No values output to txtField while reading from SQL Server database in ASP.NET

I am trying to simply read data from my SQL Server database and input them into text fields on a webform.
I can't figure out what I'm missing but everything compiles smoothly and runs but my text fields remain empty.
protected void Page_Load(object sender, EventArgs e)
{
String index = Request.Form["indexTb"];
string constr = ConfigurationManager.ConnectionStrings["TravelLogConnectionString2"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
string selectSql = "SELECT Location, Date, Message FROM EntryLogs WHERE ID='" + Convert.ToInt32(index) + "'";
SqlCommand com = new SqlCommand(selectSql, con);
try
{
con.Open();
using (SqlDataReader reader2 = com.ExecuteReader())
{
while (reader2.Read())
{
reader2.Read();
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
reader2.Close();
reader2.Dispose();
}
}
finally
{
con.Close();
}
}
You're calling the reader2.Read(); twice - once in the while loop, once just below:
while (reader2.Read())
{
reader2.Read(); // <=== WHY call .Read() a second time ?!?!!?!
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
That's both unnecessary, and could lead to no results being returned.
If your query only returns one row, the .Read() in the while loop would read that row and return it, but then the next line does another Read(), which would not return any data (since the first and only row has already been read).
Just remove that unnecessary second call to .Read() and I bet your data will begin to show up!
And to fix that glaring SQL injection - use parametrized queries! as one should always do anyway!
string selectSql = "SELECT Location, Date, Message FROM EntryLogs WHERE ID = #Id;";
SqlCommand com = new SqlCommand(selectSql, con);
com.Parameters.Add("#Id", SqlDbType.Int).Value = Convert.ToInt32(index);
try
{
con.Open();
using (SqlDataReader reader2 = com.ExecuteReader())
{
while (reader2.Read())
{
// REMOVE THIS reader2.Read();
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
reader2.Close();
reader2.Dispose();
}
}
finally
{
con.Close();
}

Using datareader to count Asp.net

I'm checking if a barcode from a database table(using a select query) exists and insert the details into another database table else the barcode does not exist. The inserts fine but I would like to count the number of barcodes entered. Say within a session an user enters 5 barcodes then the total count is 5 but my code keeps returning 1 and not incrementing.
protected void btnReturn_Click(object sender, EventArgs e)
{
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString());
//commands identifying the stored procedure
SqlCommand cmd = new SqlCommand("selectCrate", conn);
SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con);
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows) {
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode);
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter = counter + 1;
}
reader.Close();
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
You can store the number in session then do something with it when the session ends (store it in a database or whatever you want). Declare a session variable:
Session[“NumInserts”] = 0;
Then update it with each insert:
Session[“NumInserts”] = (int) Session[“NumInserts”] + 1;
That variable will be maintained as long as the session exists. Also, make sure you only declare the session variable once and don’t ever allow it to reset during the session’s life cycle. Otherwise, it will go back to 0 and give you inaccurate results.
i rechecked to make sure and i misunderstood your question which led to some confusion.
And to answer your question i don't think there is any easy solution to update realtime the numbers. Any solution of i can think of is websocket connection which I personally have no knowledge of inside webforms(Don't even know if its possible).
I formatted your code. This should give you the total rows back in one go(no realtime update on screen).
protected void btnReturn_Click(object sender, EventArgs e)
{
int counter = 0;
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString()))
{
con.Open();
//commands identifying the stored procedure
using (SqlCommand cmd = new SqlCommand("selectCrate", con))
{
using (SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con))
{
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode));
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode;
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter++;
}
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
}
}
}
}

While fetching a record in asp.net from sql server it always return null

While fetching a record in asp.net from sql server it always return null..here's code-
Even if record is available in database, object oid will have null at run time.
Please help.
thanks.
protected void btnLogin_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["DBMS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand com = new SqlCommand("select id from reg where user=#user and password=#pass", con);
com.Parameters.AddWithValue("#user", txUName.Text);
com.Parameters.AddWithValue("#pass", txPass.Text);
con.Open();
var oid = com.ExecuteScalar();
con.Close();
if (oid == null)
{
lblEr.Visible = true;
}
else
{
Session.Add("id", oid.ToString());
Session.Add("user", txUName.Text);
com = new SqlCommand("select type from dbo.reg where user=#u", con);
com.Parameters.AddWithValue("#u", txUName.Text);
con.Open();
var otype = com.ExecuteScalar();
con.Close();
var vtype = "admin";
if (vtype == otype.ToString())
{
Session.Add("admin", otype.ToString());
Response.Redirect("admin.aspx");
}
Response.Redirect("user.aspx");
}
}
It worked just by correcting following syntax-
SqlCommand com = new SqlCommand("select id from reg where [user]=#user and [password]=#pass", con);
Since 'user' is also name of a user in sql server, so when we want to use it at another place like here as column then we have to use it as [user].

why does SELECT SCOPE_IDENTITY() returning null?

I am trying to get ID generated by last Insert function. I understand very little about Scope and Session. But by reading blogs and other sources, I understood that, I should use Scope_Identity() function. But I am getting null value. Here is my code :
public int InsertUser(string username, string gender, string agegroup, string email, int partnerID, string userType)
{
try
{
string query = "Insert into tblUser (username,gender,agegroup,email,partnerid,usertype) values (#username,#gender,#age,#email,#partnerid,#usertype)";
SqlCommand cmd = new SqlCommand(query, _dbConnection.getCon());
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#age", agegroup);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#partnerid", partnerID);
cmd.Parameters.AddWithValue("#usertype", userType);
if (cmd.ExecuteNonQuery() > 0)
{
query = "select scope_identity() as id";
cmd = new SqlCommand(query, _dbConnection.getCon());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);// dt is showing no value in it
return 1;// This should return ID
}
else {
return -1;
}
}
catch (Exception e) {
throw e;
}
}
How can I achieve this?
Try appending SELECT scope_identity() to your first query and then capture the identity using var identity = cmd.ExecuteScalar() instead of running cmd.ExecuteNonQuery().

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

Resources