How to select values in ASP.NET using SQL - asp.net

I have a table in my database and two textbox and a button in my ASP.NET. I want to call database and select product name and code and if the entrance is correct I want to ok message, otherwise false!
Here is my code, but I did not get correct result.
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Code", txtCode.Text);
SqlDataReader dr = cmd.ExecuteReader();
scon.Close();
Label1.Text = "The Product is in our list.Thank you";
}
catch(Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}

Your query is modified as below
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.Add("#Name", SqlDbType.Varchar).Value = txtName.Text;--Update the datatype as per your table
cmd.Parameters.Add("#Code", SqlDbType.Varchar).Value = txtCode.Text;--Update the datatype as per your table
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
--If you want to check the whether your query has returned something or not then below statement should be ommitted. Else you can check for a specific value while reader is reading from the dataset.
while (dr.Read())
{
--The returned data may be an enumerable list or if you are checking for the rows the read statement may be ommitted.
--To get the data from the reader you can specify the column name.
--for example
--Label1.Text=dr["somecolumnname"].ToString();
Label1.Text = "The Product is in our list.Thank you";
}
}
else
{
Label1.Text = "The Product is not in our list.Sorry!";
}
scon.Close();
}
catch (Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}
Hope this answer will help you in resolving your query.

Related

Getting error from accessing DataReader value (accessing joined table results in SqlDataReader)

UPDATE - PROBLEM SOLVED
Just in case to retrieve all data at once, using a single SQL statement to retrieve joined table results, but couldn't access it and received error below
Exception details: System.IndexOutOfRangeException: crsName
By the way, anyone please suggest a more convenient way to deal with a GridView that need to display a JOIN result.
Instead of this approach - https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.datacontrolfieldcollection.add?view=netframework-4.8
BoundField courseBF = new BoundField();
courseBF.DataField="courseName";
courseBF.HeaderText="Course Name";
//Which is stated in Microsoft Document
Here's the code receive error
string userID = (string)Session["userID"];
string sql = "SELECT courseID from gpaSem where stuID=#userID";
string temp = "";
string temp02 = "";
string[] crsID;
string[] crsName;
string[] grade;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#userID", userID);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
temp += ("!" + dr["courseID"]);
}
crsID = temp.Split('!');
crsID = crsID.Skip(1).ToArray();//course ID get
dr.Close();
con.Close();
con.Open();
temp = "";
foreach (string crs in crsID)
{
sql = "SELECT G.grade AS grade, C.crsName AS crsName FROM gpaSem G, course C WHERE G.courseID=C.courseID AND G.courseID=#courseID";
cmd.Parameters.AddWithValue("#courseID", crs);
dr = cmd.ExecuteReader();
if(dr.Read())
{
temp += "!" + dr["crsName"];//error
temp02 += "!" + dr["grade"];
}
}
crsName = temp.Split('!');
crsName = crsName.Skip(1).ToArray();//course name get
grade = temp02.Split('!');
grade = grade.Skip(1).ToArray();//grade get
dr.Close();
con.Close();
My point is, is that I should explicitly use JOIN in SQL statement or the way I access the value is wrong?

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

I need to loop for all records in my table

I need to loop for all records in my table , cose here is not working properly in my project "Auction web system" , I use web service here to check the status of product Periodically , and when the status is opened and data time is less to now , update the product and set its status to "closed". the code here work only for one row at the time ! I need to check for all rows at the same time.
{ string sql12 = "SELECT item_id FROM items Where status='opened' AND endDate<=#endate ";
SqlCommand cmd12 = new SqlCommand(sql12, con);
con.Open();
cmd12.Parameters.AddWithValue("#endate", DateTime.Now);
query = Convert.ToInt32(cmd12.ExecuteScalar());
string sql123 = "UPDATE items SET status ='closed' WHERE item_id =#Item_ID";
SqlCommand cmd21 = new SqlCommand(sql123, con);
cmd21.Parameters.AddWithValue("#Item_ID", query);
cmd21.ExecuteNonQuery();
con.Close();
CalculateWinningPrice(query);
}
public void CalculateWinningPrice(Int32 query)
{
string sql1 = "SELECT MAX(Bid_price) AS Expr1 FROM Bid WHERE (item_id = #Item_ID)";
SqlCommand cmd1 = new SqlCommand(sql1, con);
con.Open();
cmd1.Parameters.AddWithValue("#Item_ID", query);
Int32 max = Convert.ToInt32(cmd1.ExecuteScalar());
SqlCommand cmd3 = new SqlCommand("SELECT user_id FROM Bid WHERE(Bid_price =(SELECT MAX(Bid_price) AS Expr1 FROM Bid AS BID_1 WHERE(item_id = #Item_ID)))", con);
cmd3.Parameters.AddWithValue("#Item_ID", query);
Int32 winner = Convert.ToInt32(cmd3.ExecuteScalar());
SqlCommand cmd4 = new SqlCommand("SELECT name FROM items WHERE (item_id=#Item_ID)",con);
cmd4.Parameters.AddWithValue("Item_ID", query);
string product_name = Convert.ToString(cmd4.ExecuteScalar());
GeneratePDF.create_pdf(product_name, Convert.ToDecimal(max).ToString("c"), DateTime.Now.ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO Winners VALUES(#item_id, #user_id,#win_price,#win_date)");
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#item_id", query);
cmd.Parameters.AddWithValue("#user_id", winner);
cmd.Parameters.AddWithValue("#win_price", max);
cmd.Parameters.AddWithValue("#win_date", DateTime.Now);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
Get results into a datareader MSFT DOCU
then wrap the rest of the code in
while(reader.Read())
{
REST OF CODE
}
This question might also help you.
Reader Question
you can directly update your table by this query
UPDATE items SET status ='closed' WHERE item_id in(SELECT item_id FROM items Where status='opened' AND endDate<=#endate)

There is already an open DataReader associated with this Command which must be closed first.Why?

protected void Page_Load(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex=0;
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = '" + Login1.UserName + "'";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
SqlDataReader dr = cmdr.ExecuteReader();
if (cmdr.ExecuteReader().HasRows)//here showing the error as the title i gave.
{
Session["userName"] = Login1.UserName.Trim();
string myStringVariable = "Welcome! ";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + Login1.UserName + "');", true);
//dr.Dispose();
}
else
{
string myStringVariable = " No Username Found";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + "');", true);
}
con.Close();
}
I used datareader object dr in the same page in other events too...
Plz help....
Why are you calling ExecuteReader two times? One is enough
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)
{
-----
Your code has also other problems. Sql Injection is the most Dangerous. You should use code like this when passing values entered by your user
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on " +
"t1.RegId = t2.RegId and t2.Uname = #uname";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
cmdr.Parameters.AddWithValue("#uname", Login1.UserName);
SqlDataReader dr = cmdr.ExecuteReader();
and also using a global connection is a bad practice because you keep an expensive resource locked. Try to use the using statement, open the connection, the command and the reader and then close and destroy everything
// CREATE CONNECTION AND COMMAND
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmdr = new SqlCommand(str, con))
{
// OPEN THE CONNECTION
con.Open();
cmdr.Parameters.AddWithValue("#uname", Login1.UserName);
using(SqlDataReader dr = cmdr.ExecuteReader())
{
// USE
....
} // CLOSE AND DESTROY
} // CLOSE AND DESTROY
You've already opened the reader in the line above. I think you want:
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)//here showing the error as the title i gave.
But there are other issues - SQL Injection as #Brad M points out (do a search on parameterised queries), and you're leaking your command objects - they ought to be enclosed in using statements.
I'm also slightly nervous about what/where con is defined - it smells strongly like a global variable of some kind. The general pattern for using ADO.Net is to, inside a single method/block of code, you should create a new SqlConnection object (inside a using statement), create a new SqlCommand object (inside a using statement), open the connection, execute the command, process the results (if applicable) and then exit the using blocks and let everything get cleaned up. Don't try to share SqlConnection objects around.
you already execute reader on
SqlDataReader dr = cmdr.ExecuteReader();
So in if, you should use existing reader
dr.HasRows
Initialy be careful in your sql scripts
Avoid
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = '" + Login1.UserName + "'";
Use
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = #username";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
cmdr.Parameters.AddWithValue("#username", Login1.UserName);
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)
{
Session["userName"] = Login1.UserName.Trim();
string myStringVariable = "Welcome! ";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + Login1.UserName + "');", true);
}
and DO NOT forget to
dr.Close();

How to check two different webforms having same value of textboxes

aspx
TextBox1.Text
World.aspx
TextBox1.Text
I want the pages Hello.aspx and World.aspx having same value of validation
please help me anybody have the idea about this
You need to save the value on the first page using cookies or database or something else.
Then retrieve the value in the second page and compare the values in the validation function or event.
using(SqlConnection cn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn;
string sql = string.Format(#"select email from customers where customer_id = '{0}'", customer_id);
cmd.CommandType = CommandType.Text;
//try and catch block would go here
cmd.CommandText = sql;
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
string email = rdr[0].ToString();
cn.Close();
}
}

Resources