Execute reader connection error - c#

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True ");
con.Open();
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName'" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}

where username **=**
forgot equality sign
Also, the conenction you open and the connection you use are different

The way I see it, you open a connection to the SQL server in Page_Load handler. But you don't close it.
If you try to open another one, or try to execute on a closed SqlConnection object, you might get an error.
A good way to do this is do something like this:
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
//do something here
}
catch (Exception)
{
/*Handle error*/
}
}

SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True");
con.Open();
}
catch
{
//Handles exceptions here
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
try
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName='" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}
finally
{
con.Close();
}
}

If you code for login, then here a neat version code, Depend on your flagset you can redirect or display wrong password msg
bool flagset=false;
SqlDataReader dr;
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select password from TestDemo where userName=#uName";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#uName", txtusername.Text);
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows){
while (dr.Read())
{
if(dr[0].ToString()==txtusername.Text)
{ flagset=true; }
}
}dr.Close();
con.Close();
}
}return flagset;

Related

quiz with choices using datareader. clicking button to change from number 1 to 4

click a button to change the question in my Form and choices.. but this code only shows the last data of my table when i click it
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
im only starting in sql server
you should add some int type of data and you should check it from you sql statement then
you can get your willing data from database it something like this
don't forget to increment it in somewhere of you program and keep in mind of boundary of it
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question where id ="+one, conn);
public class Form1
{
private SqlConnection conn;
private SqlCommand command;
private SqlDataReader reader;
public Form1()
{
conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
command = new SqlCommand("SELECT * "+ "FROM question", conn);
try
{
conn.Open();
reader = command.ExecuteReader();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
else reader.Close();
}
}

How can I use transaction in this code?

I was trying to use this code without transaction but it gave me error, so I want to use it with transaction. How I can use it?
My code is:
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query = "insert into users(Name, Password) values('ubaid', 'ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
SqlTransaction trans;
private void btn_Update_Click(object sender, EventArgs e)
{
try
{
con.Open();
trans = con.BeginTransaction(); // Begins transaction
string query = "insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
trans.Commit();
}
catch (Exception ex) //error occurred
{
trans.Rollback(); // Rollback transaction on error
}
}
Try the above code. Hope it helps you.

Unable to post data in drop down list from DB

I am new in writing code. Getting following error when trying to post data in drop down list from DB.
My Objective is: Post data in Drop Down List from DB.
Error message: Process can't access the file because it is being used
by another process
using System.Data;
using System.Configuration;
public partial class Default : System.Web.UI.Page
{
//SqlCommand cmd;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Database=Database1;AttachDbFilename=C:\Database1.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
Populate1();
}
protected void Button1_Click1(object sender, EventArgs e)
{
/* SqlCommand cmd = new SqlCommand("insert into service_type (type) values(' " + TextBox1.Text + " ')",
new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
cmd.Connection.Close();
cmd.Connection.Dispose(); */
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into service_type (type) values(' " + TextBox1.Text + " ')";
cmd.ExecuteNonQuery();
con.Close();
}
public void Populate1()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [serice_type]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
DropDownList1.DataSource = ddlValues;
DropDownList1.DataValueField = "theType";
DropDownList1.DataTextField = "theType";
DropDownList1.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
}

DropdownListSelectedValue to Label

I keep on getting the Name instead of the Price.What I want is I pick a value on The DropdownList and Load its price on the label.
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
while (rdr.Read())
{
lblPrice.Text = DropDownList1.SelectedValue.ToString();
}
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
lblPrice.Text=DropDownList1.SelectedItem.Value.ToString();
}
above is my selectedIndex.
Change your code into this:
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if(dr.HasRows)
{
while (rdr.Read())
{
lblPrice.Text = rdr.GetValue(0).ToString(); // if price is string use GetString(0))
}
}
connection.Close();
}
EDIT:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GetData();
}

Why does this UPDATE command not update the data, even though there is no error?

I have a users table having fields uname, ushortname and pswd as well ucode as primary key.
The following UPDATE is not working:
protected void Page_Load(object sender, EventArgs e)
{
string uname = Request.QueryString["uname"];
string ucode = Request.QueryString["ucode"];
if (!string.IsNullOrEmpty(uname))
{
SqlCommand cmd = new SqlCommand("select * from users WHERE ucode=#ucode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtUserName.ReadOnly = false;
txtUserShortName.ReadOnly = false;
txtPassword.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#ucode", ucode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
LblUcode.Text = dr["ucode"].ToString();
txtPassword.Text=dr["pswd"].ToString();
txtUserShortName.Text = dr["ushortname"].ToString();
txtUserName.Text = dr["uname"].ToString();
}
dr.Close();
conn.Close();
}
}
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", LblUcode.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
There is no error, the data simply isn't being updated.
You need to make sure the parameter names match exactly what they do in your sql string.
cmd.Parameters.AddWithValue("#UCODE", UCODE);
Also, either wrap all of that in a using or try/finally to dispose of the connection. I'm assuming you've already got code to open the connection before trying to execute it.
Try this:-
using(SqlConnection conn = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE ", conn))
{
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", UCODE);
conn.Open();
cmd.ExecuteNonQuery();
}
}
You are missing # in Ucode. Also, its a good practice to wrap your code inside using block check this.
See the edited below code:-
if (!PostBack)
{
string databaseconnectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
string sql = "update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE";
using (SqlConnection conn = new SqlConnection(databaseconnectionstring))
{
conn.Open();
using (SqlCommand cmd= new SqlCommand())
{
cmd.CommandText=sql;
cmd.Connection=databaseconnectionstring;
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
string bsname = Request.QueryString["bsname"];
string bscode = Request.QueryString["bscode"];
if (!string.IsNullOrEmpty(bsname))
{
if (string.IsNullOrEmpty(txtBsName.Text))
{
SqlCommand cmd = new SqlCommand("select * from bs WHERE bscode=#bscode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtBsName.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#bscode", bscode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lblBsCode.Text = dr["bscode"].ToString();
txtBsName.Text = dr["bsname"].ToString();
}
dr.Close();
conn.Close();
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
conn.Open();
string UCODE = LblUcode.Text;
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Company Data update Successfully......!");
clear();
}
Thank you all its working now with the help of above code.

Categories

Resources