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();
}
Related
Here is the code of my .aspx page,
When I click on update it runs the page doesn't show any errors and the row is not updated in my blog table.
The exception doesn't display anything, and i have a row with the id in my table.
The select command in the Page_Load() works perfectly.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Blog
{
public partial class update : System.Web.UI.Page
{
SqlConnection connection = new SqlConnection(##################);
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["id"];
string sql = "select * from blog where Id=#id";
SqlCommand sqlCommand = new SqlCommand(sql,connection);
sqlCommand.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader dataReader = sqlCommand.ExecuteReader();
while (dataReader.Read())
{
DropDownListCategory.SelectedIndex = DropDownListCategory.Items.IndexOf(DropDownListCategory.Items.FindByText(dataReader["category"].ToString().Trim()));
TextBoxTitle.Text = dataReader["title"].ToString();
TextBoxDesc.Text = dataReader["description"].ToString();
}
connection.Close();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
LabelDate.Text = DateTime.Now.ToString();
}
protected void Update_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(Request.QueryString["id"].Trim());
string sql2 = "UPDATE blog SET title = #title , category = #category , description = #description , posteddate = #posteddate WHERE Id=#id";
connection.Open();
SqlCommand sqlCommand2 = new SqlCommand(sql2, connection);
sqlCommand2.Parameters.AddWithValue("#id", id);
sqlCommand2.Parameters.AddWithValue("#title", TextBoxTitle.Text);
sqlCommand2.Parameters.AddWithValue("#category", DropDownListCategory.SelectedItem.Text.ToString());
sqlCommand2.Parameters.AddWithValue("#description", TextBoxDesc.Text);
sqlCommand2.Parameters.AddWithValue("#posteddate", DateTime.Now.ToString());
sqlCommand2.ExecuteNonQuery();
}
catch(Exception ex)
{
Label1.Text = ex.Message;
}
connection.Close();
//Response.Redirect("Default.aspx");
}
}
}
Added a if(!IsPostBack){} now works fine, Thank you
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"];
string sql = "select * from blog where Id=#id";
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader dataReader = sqlCommand.ExecuteReader();
while (dataReader.Read())
{
DropDownListCategory.SelectedIndex = DropDownListCategory.Items.IndexOf(DropDownListCategory.Items.FindByText(dataReader["category"].ToString().Trim()));
TextBoxTitle.Text = dataReader["title"].ToString();
TextBoxDesc.Text = dataReader["description"].ToString();
}
connection.Close();
}
}
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();
}
}
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();
}
I have the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace SalesSystem
{
public partial class Order : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local);Initial Catalog=MOE;Integrated Security=True";
conn.Open();
SqlCommand da = new SqlCommand("Select Itemid,ItemName from Item", conn);
DropDownList1.DataSource = da.ExecuteReader();
DropDownList1.DataTextField = "Itemname";
DropDownList1.DataValueField = "Itemid";
DropDownList1.DataBind();
conn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
string orderdate = txtorderdate.Text;
string customerid = txtcustomerid.Text;
string itemid = DropDownList1.SelectedValue;
string qty = txtquantity.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=MOE;Integrated Security=True";
con.Open();
SqlCommand result = new SqlCommand("Insert Into [Order](Orderdate,Customerid,Itemid,OQty) Values ('" + orderdate + "','" + customerid + "','" + itemid + "','" + qty + "')", con);
result.ExecuteNonQuery();
}
}
}
Whenever I run this and click the "Add" button, the value of the dropdown list (itemid) is always inserted as the first value (001) not matter how many times I changed the dropdown list value.
It is rebinding after every post back. check this to make sure your drop down is bound only once during the first page load but not when you click Button
protected void Page_Load(object sender, EventArgs e)
{
try
{
if(!IsPostBack)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local);Initial Catalog=MOE;Integrated Security=True";
conn.Open();
SqlCommand da = new SqlCommand("Select Itemid,ItemName from Item", conn);
DropDownList1.DataSource = da.ExecuteReader();
DropDownList1.DataTextField = "Itemname";
DropDownList1.DataValueField = "Itemid";
DropDownList1.DataBind();
conn.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
I have two query's in C# running in a datagridview, one is to show all data. the other is set to display in the footer. The footer is showing, just not displaying my query.
query one (with footer)
protected void Button2_Click(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.ShowFooter = true;
dg.DataSource = dgl;
dg.DataBind();
cs.Close();
}
**query two(footer query)**
protected void dg_DataBound(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
String totalDonations = Convert.ToString(cmd.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[3].Text = totalDonations;
}
the datagrid shows query one works well, the footer even shows but it has not got any data.
Although you have it working, there are ways to improve it.
In the first method, using statement would manage the connection better:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con))
{
da.Fill(dt);
}
}
dg.ShowFooter = true;
dg.DataSource = dt;
dg.DataBind();
}
And the second method:
protected void dg_DataBound(object sender, EventArgs e)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
dg.FooterRow.Cells[3].Text = totalDonations;
}
Probably I would use GridView's RowDataBound to write into footer where I can can know the type of row:
protected void dg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
e.Row.Cells[3].Text = totalDonations;
}
}
EDIT : Here's the markup I have used to test:
<asp:GridView ID="dg" runat="server" AutoGenerateColumns="true" OnDataBound="dg_DataBound" ShowFooter="true">
</asp:GridView>
After hours of problems, I have solved it.
corrected code
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
MySqlCommand cmdtwo = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.DataSource = dgl;
dg.ShowFooter = true;
dg.DataBind();
cs.Close();
cs.Open();
string totalDonations = Convert.ToString(cmdtwo.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[7].Text = "Total £";
dg.FooterRow.Cells[8].Text = totalDonations;
}
although I am sure there is a better way of doing this, if you know please feel free to edit.