Using datareader to count Asp.net - 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!!";
}
}
}
}
}
}

Related

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

Using sqldatareader in another sqldatareader

I'm checking table to see if ID exists in table A if that ID exists insert it in table B but I also would like to check in table B if that ID number was not already inserted. But my issue is that I'm not able to combine all of that together. I'm not sure how to put a sqldatareader into another.
SqlCommand cmd1 = new SqlCommand("CreateID", con);
SqlCommand cmd = new SqlCommand("selectID", conn);
SqlCommand com = new SqlCommand("SelectIDfromtableB", con);
public SqlDataReader dr;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
sessionCount++;
Session["Count"] = sessionCount;
cmd1.Parameters.Add("#crate_box_no", SqlDbType.NVarChar).Value = id;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
}
reader.Close();
cmd1.ExecuteNonQuery();
}
else
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert( Id number does not exist'); window.location.href = 'Return.aspx';", true);
}
}
if (dr.Read())
{
lblError.Text = "Data was inserted before";
}
dr.Close();
You can minimize the code, use one connection for all the readers and one command, but you have to set the CommandText each time and clear the parameters if there were any. Use the using keyword to make sure your resources are disposed.
If there is anything you need to check in your first command, you can set a flag
using (var conn = GetTheConnection())
{
conn.Open();
//flag to check if id exists
var idExists = false;
var cmd= new SqlCommand("CreateID", conn );
cmd.Parameters.Add("#crate_box_no", SqlDbType.NVarChar).Value = id;
using (var myReader = cmd.ExecuteReader())
{
if(myReader.Read())
{
idExists = true;
}
}
//clear parameters
if (idExists)
{
cmd.Parameters.Clear();
cmd.commandText = "You 2nd SQL Script here"
using (var myReader = cmd.ExecuteReader())
{
}
}
}
Cant you just do 2 queries? First one counting rows of id occurences, if greater 0 then count occurences in table b, if 0 continue?
Edit Example pseudo code:
command1 = "select id from tableA where id = toLookForId";
Define GridView1 and Gridview2;
Gridview1.datasource = sqldatareader.executenonquery(command1);
Gridview1.databind();
if gridview1.rows.count > 0 then
command2 = "select id from tableB where id = toLookForId";
Gridview2.datasource = sqlreader.executenonquery(command2);
gridview2.databind();
if gridview2.rows.count = 0 then
//your code goes here
else
//id exists so quit
return;
end if
end if
Regards,
Maheshvara

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"];
}

sql data reader class

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;
}
}
}

Resources