How to check two different webforms having same value of textboxes - asp.net

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

Related

How to select values in ASP.NET using SQL

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.

There is no row at position 0, exception

I am having a problem while login, the registered user's name, email and password is saved in the database and the email is the username. When i am logging through email and password it shows the error "There is no row at position 0."
Here's my code :
con.Open();
cmd = new SqlCommand("select * from userinfo where username='" + t1.Text.ToString() + "' and password='" + t2.Text.ToString() + "'", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
con.Close();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #username AND password = #password", con);
cmd.Paramater.AddWithValue("#username", t1.Text.ToString());
cmd.Paramater.AddWithValue("#password", t2.Text.ToString());
con.open();
SqlDataReader dr = cmd.ExecuteReader();
dr.read();
if(dr.hasRows){
Session["name"] = dr["username"].ToString();
}
con.close();
Try not to throw variables into a sql command. SQL injection and all. Try and pass the paramater
Because reason is the no one record found in Db same as a passing username and password and you can directly access so its give exception. Please add one if condition below like.
con.Open();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #username AND password = #password", con);
cmd.Paramater.AddWithValue("#username", t1.Text.ToString());
cmd.Paramater.AddWithValue("#password", t2.Text.ToString());
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
if(ds.Tables["abc"].Rows.Count>0)
{
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
}
con.Close();
The exception is because there are no records in that table.
There are no rows, so there is no Rows[0].
Try something like this:
using (var con = new SqlConnection(connectionString))
{
con.Open();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #1 AND password = #2", con);
cmd.Paramater.AddWithValue("#1", t1.Text);
cmd.Paramater.AddWithValue("#2", t2.Text);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
if(ds.Tables["abc"].Rows.Any())
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
con.Close();
}
You should use parameters when constructing SQL queries to avoid injection attacks.
Don't forget that SqlConnection is IDisposable, so should be in a using statement (you might already be doing this, but i've included it here just in case).
It also looks like the user's password is being compared to the input from a TextBox (or a similar control)? If so, the user's password should not be stored in plain text in the database as this is a security issue. Consider hashing the stored password, doing the same with the user's input, and comparing that instead.
This wasn't part of the question, I know, but worth pointing out just in case.

ASP ServerVariables logon user

In my code behind, I have this
{
Label2.Text = "[" + HttpContext.Current.User.Identity.Name + "]";
}
to identify the username in domain. So far so good. It works properly in IIS.
However, I would like to store the username into a database. How can I do that?
The idea is to record the person who answer to this:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile) VALUES (#Business,#Business2,#Mobile)";
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}
I have the answer inserted into the database, but how can I save the person who answer? Can I save the label into the database table? Or is it impossible?
Just add a username field to your table and add another parameter:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile,username) VALUES (#Business,#Business2,#Mobile,#username)";
using (Conn) {
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.Parameters.AddWithValue("#username", HttpContext.Current.User.Identity.Name);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}

how to store primary key in session with stored procedure

I have login page for which I have used stored procedure. I am using session to store id of user which is primary key. When I enter wrong username and password it should redirect to some other page but it is giving me exception as "Object reference not set to an instance of an object." My code for login.aspx.cs is:
SqlCommand cmd1 = new SqlCommand("select artistId from artist where Username=#username and Artistpass=#password",con);
cmd1.Parameters.AddWithValue("#username", txtusr.Text);
cmd1.Parameters.AddWithValue("#password", txtpass.Text);
con.Close();
Session["username"] = txtusr.Text;
SqlParameter param = new SqlParameter("#username", txtusr.Text.Trim());
SqlParameter param1 = new SqlParameter("#password", txtpass.Text.Trim());
SqlCommand cmd = new SqlCommand("login", con);
cmd.Parameters.Add(param);
cmd.Parameters.Add(param1);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.Redirect("afterlogin.aspx");
}
else
{
MessageBox.Show("Login Unsuccessful");
}
con.Close();
if (con.State != ConnectionState.Open)
{
con.Open();
}
int id = (int)cmd1.ExecuteScalar();
Session["ID"] = id;
con.Close();
plz help.
ExecuteScalar returns null if your where statement doesn't find a match for your user and password
So you cannot cast a null return value to an integer
object id = cmd1.ExecuteScalar();
Session["ID"] = id;
con.Close();
this, of course, means that you need to check the Session["ID"] variable in the redirected page to see it it is null

i want to use data reader & update statement at same time

here is code
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
mon = mon - 1; //because month array is with 0
Label1.Text = day.ToString();
if (day==21)
{
int j = 1;
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = MyConn;
cmd1.CommandText = "SELECT No_of_times,Dustbin_no from mounthly_data";
SqlDataReader MyReader = cmd1.ExecuteReader();
while (MyReader.Read())
{
String a = MyReader["No_of_times"].ToString();
String b = MyReader["Dustbin_no"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set [" + month[mon] + "]='"+a+"' where Dustbin_no='"+b+"'"; //just see ["+month[mon+"] it's imp
i = cmd.ExecuteNonQuery();
}
MyReader.Close();
}
i got error as
There is already an open DataReader associated with this Command which must be closed first.
I think you should give us the rest of the code above this code block because I'm not sure how a ExecuteNonQuery is using up a datareader. But from what I can gather, what you probably want is to open two separate connections. Only one datareader can be open per connection at a time. Either you use two separate connections or you could maybe use a datatable/dataset for the result of both your queries.
EDIT: From the rest of your code, yes, using two connections would be the simplest answer. When a reader is open, the connection associated with it is dedicated to the command that is used, thus no other command can use that connection.
I would recommend using a DataTable as this OLEDB example shows:
public static void TrySomethingLikeThis()
{
try
{
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = Users.GetConnectionString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.AsEnumerable())
{
cmd.CommandText = "UPDATE Customers SET CustomerName='Ronnie' WHERE ID = 4";
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Resources