Unable to post data in drop down list from DB - c#

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

Related

Get ID of selected value in drop down

I am trying to save data in my database, as part of that I am trying to get the ID (primary key) of my selected item in my drop down.
It keeps saving the same ID all the time. It only saves the first ID of any chosen item. How can I adjust my code so that it saves the different IDs based on what I have chosen in my drop down
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "RoleType";
DropDownList1.DataValueField = "UserRoleID";
DropDownList1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("sp_UserInsertUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
String ID = DropDownList1.SelectedValue;
cmd.Parameters.AddWithValue("UserID", (hfUserID.Value == "" ? 0 : Convert.ToInt32(hfUserID.Value)));
cmd.Parameters.AddWithValue("UserRoleID", ID);
cmd.Parameters.AddWithValue("Username", TextBox1.Text);
cmd.Parameters.AddWithValue("Password", TextBox2.Text);
cmd.Parameters.AddWithValue("Email", TextBox3.Text);
cmd.Parameters.AddWithValue("DateCreate", TextBox4.Text);
cmd.ExecuteNonQuery();
con.Close();
}
This is because every time you click on button. click event is occurred but before that it executes the Page Load event and In page load event you have added the logic of binding drop down. it means whenever you click button then every time it first load the drop down list then comes to the click event. for this purpose you just need to add one if condition using IsPostBack.
Make the changes as below
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) //Added
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "RoleType";
DropDownList1.DataValueField = "UserRoleID";
DropDownList1.DataBind();
}
}
You should check !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) // Add this If condition
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "RoleType";
DropDownList1.DataValueField = "UserRoleID";
DropDownList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("sp_UserInsertUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
String ID = DropDownList1.SelectedValue;
cmd.Parameters.AddWithValue("UserID", (hfUserID.Value == "" ? 0 : Convert.ToInt32(hfUserID.Value)));
cmd.Parameters.AddWithValue("UserRoleID", ID);
cmd.Parameters.AddWithValue("Username", TextBox1.Text);
cmd.Parameters.AddWithValue("Password", TextBox2.Text);
cmd.Parameters.AddWithValue("Email", TextBox3.Text);
cmd.Parameters.AddWithValue("DateCreate", TextBox4.Text);
cmd.ExecuteNonQuery();
con.Close();
}

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.

Execute reader connection error

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;

How to insert Label values into MS Access Table?

Hi i want to basically insert the values in the labels to a table in ms access.
I have done it for textbox and it stores but for Label When i try to store it no error shows up but it does not store in the database what should i do? I am using the following code
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string str = "insert into Orders (Products, Amount)" + " values (#p1, #p2)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Label18.Text);
cmd.Parameters.AddWithValue("#p2", Label16.Text);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
Console.WriteLine("Exception Occured");
}
finally
{
if (con != null && con.State != ConnectionState.Closed)
{ con.Close(); }
}
}
Also i tried storing textbox value into the same Table "Orders" under the column "Address" but facing the same above issue...The table does not update. I have used this code before for other textboxes etc for different tables and it has worked fine..
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Button1_Click(object sender, EventArgs e)
{
{
string str = "insert into Orders (Address)" + " values (#p1)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement
try with
string str = "insert into Orders (Products, Amount) values (?,?)";
You can change the code as below
protected void Button1_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb"))
using (OleDbCommand cmd = new OleDbCommand("insert into Orders (Products, Amount) values (?,?)", con))
{
cmd.Parameters.AddWithValue("#p1", Label18.Text);
cmd.Parameters.AddWithValue("#p2", int.Parse(Label16.Text));
con.Open();
int no = cmd.ExecuteNonQuery();
Console.WriteLine("number of rows affected = " + no);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Occured :" ex.ToString());
}
}

How to display data from database into textbox, and update it

I can display my data in my textbox, dropdownlist after retrieve data from sql database, but when i proceed with my update button, the information edited in the textbox or dropdownlist wouldn't update into the database. I tried to remove the code in page load, and re-key in all the data manually, it can be update. All I want is retrieve data from database and display it in the textbox, and it can be update into the database after make some changes from the textbox. Can someone help me on this? Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class UpdateCustomerDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE customer_registration SET password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno where username='" + Session["username"] + "'", con);
con.Open();
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text + DropDownListMonth.Text + DropDownListYear.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
}
Wrap your all statements in !IsPostBack condition on page load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// all statements
}
}
This will fix your issue.
The answer is .IsPostBack as suggested by #Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load
private void PopulateFields()
{
using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}//end using
}
Then call it in your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateFields();
}
}
protected void Page_Load(object sender, EventArgs e)
{
DropDownTitle();
}
protected void DropDownTitle()
{
if (!Page.IsPostBack)
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "Select";
newItem.Value = "0";
ForumTitleList.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem1 = new ListItem();
newItem1.Text = reader["ForumTitles"].ToString();
newItem1.Value = reader["ForumTitlesID"].ToString();
ForumTitleList.Items.Add(newItem1);
}
reader.Close();
reader.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Populate the text box values in the Page Init event as opposed to using the Postback.
protected void Page_Init(object sender, EventArgs e)
{
DropDownTitle();
}

Categories

Resources