updated values are not getting stored in the textbox - c#

protected void Page_Load(object sender, EventArgs e)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
//Button click function
protected void Button1_Click(object sender, EventArgs e)
{
cn.Open();
st = "update patient_db set address ='" + TextBox1.Text + "' ,phone=" + TextBox2.Text+"where unique_id=123";
cmd = new SqlCommand(st, cn);
int result2 = cmd.ExecuteNonQuery();
if (Convert.ToBoolean(result2))
{
result1.Text = "details updated successfully";
}
cn.Close();
}
After assigning the value to textbox from the database,if I type some other new value in the text box,it is not taking the new value,it still persists with the old value.May i know the reason and solution for this? thanks in advance

Write a method LoadData, move the code from page_load into this method. Then call this method from page_load wrapped in a if(!IsPostBack)-check. Call this method also from the button-click event handler after you've updated the values.
private void LoadData()
{
using (var cn = new SqlConnection("Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True"))
{
cn.Open();
using(var cmd = new SqlCommand("select * from patient_db where unique_id = 123", cn))
using (var dr = cmd.ExecuteReader())
{
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
LoadData();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// ... update
LoadData();
}
Important notes:
Also use the using-statement for every object implementing IDisposable like the connection or the datareader. On that way all unmanaged resources are disposed properly. Even in case of an error.
If 123 is just an example and actually is a value provided by the user use sql-parameters to prevent sql-injection. No, use them always.

Add IsPostBack control at Page_Load method. Because before Button_Click event Page_Load event firing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}

You need to check page.Ispostback property in your page Load.
Here is your code.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
When you click on button then it will first call PageLoad event. So it will again set your old value to textbox and then it will call update method. So Update method will update old value to database.

Related

My delete function is not removing entries and is being ignored

I am having problems getting my delete function to work in my ASP.net (C#) web application and I really have no idea where to go next.
The function is called on button clicked but it is as if the Page_Load method is completely ignoring the command. I'm new to this and would appreciate some help.
Thanks.
Here is the Page_load, the DisplayData method, the Count method and the delete method which is called from a button click.
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection cn;
static int count = 1;
static int max = 2;
static String sqlQuery = "Select * from Footballer";
static bool firstTime = true;
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
SqlCommand command = cn.CreateCommand();
cn.Open();
mycount();
if (firstTime == true)
{
displayData();
firstTime = false;
}
}
protected void mycount()
{ // count no of els in table
max = 0;
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
protected void displayData()
{
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++)
reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
protected void deleteData()
{
var cmd = cn.CreateCommand();
string query = "DELETE FROM [Footballer] WHERE [PlayerName] = #name";
cmd.CommandText = query;
string name = TextBox4.Text;
cmd.Parameters.AddWithValue("#name", name);
cmd.ExecuteNonQuery();
}
}
From the code, it looks like Textbox4 value is getting overwritten before the Delete, Page_load will get called for each postback including button click event. The flag bool firstTime = true doesn't work for the purpose you are trying to achieve. I believe you want to load text box data only when the page loads first time. so you should modify the Page_load event to use IsPostBack property instead of firstTime flag, like below.
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
SqlCommand command = cn.CreateCommand();
cn.Open();
mycount();
if(!IsPostBack)
{
displayData();
}
}
This will ensure that, TextBox4 value entered by you in UI won't get overwritten when you click delete button and delete code should work as expected
Don't open the connection in Page_Load only open it where needed. Also use using to properly dispose of your resources.
public partial class WebForm1 : System.Web.UI.Page
{
//You should really pull this from your web.config
string connectionString = "(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";;
static int count = 1;
static int max = 2;
static String sqlQuery = "Select * from Footballer";
static bool firstTime = true;
protected void Page_Load(object sender, EventArgs e)
{
mycount();
if (firstTime == true)
{
displayData();
firstTime = false;
}
}
protected void mycount()
{ // count no of els in table
max = 0;
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
}
}
protected void displayData()
{
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++) reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
}
}
protected void deleteData()
{
//Add A break point here to ensure the method is hit
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
string query = "DELETE from [Footballer] where [PlayerName] = #name";
cmd.CommandText = query;
string name = TextBox4.Text;
//When stepping through in debug mode, make sure
//name is what you expect.
cmd.Parameters.AddWithValue("#name", name);
cmd.ExecuteNonQuery();
}
}
}
Note, I've done all this in the SO editor so I may have missed some closing }

How to Put two DataValueFields?

How do I bind a product name, then get a product id and price in the label result? The three attributes are from the same table in DB.
Code:
public partial class CreateOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "productName";
ddlProduct.DataValueField = "IDANDPRICE";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT productName, productID,productPrice,(productID + '-' + productPrice) AS IDANDPRICE from Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.ToString() ;
}
I find the following errors:
1- cast number filed to nvarchar in sql query
2- set AutoPostBack property of listbox to true
3- use ddlProduct.SelectedItem.Value for label2
I create a page and use your code and apply above suggestion, the following code work perfectly.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "name";
ddlProduct.DataValueField = "IdAndName";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT Id,Name,CAST( id as nvarchar(10) )+'-'+Name as IdAndName FROM Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.Value;
}
}

Asp Dropdownlist does not return selected value. (Dropdownlist is Databound)

I have created a dropdownlist, which loads its data from a table column. Now I want to select the value of dropdownlist on Index_change_event.
protected void Page_Load(object sender, EventArgs e)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
//arr = Session["arr"].ToString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
}
Remove if (!IsPostBack) from DropDownList1_SelectedIndexChanged event and if (!IsPostBack) should be on Page_Load event.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
}
}
You are only checking !IsPostBack. As the event is firing from a postback this will never be run. Also, be careful that you are not re-binding the datasource and therefore changing the selected value on page_load.

How to get value from database to a label?

I have a table from a database, i want display a value from table to my label1. This is my code:
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
but after that, i must click on this label to display the value. What can i do with this code to display my value in label while don't need click to anything?
As #wqrahd said
protected void Page_Load(object sender, EventArgs e)
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
place this code in page_load method of your WinForm.
Write a different function with your code and call it in page_load events and other events if required:
protected void Page_Load(object sender, EventArgs e)
{
setLableText();
}
private void setLableText()
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
}
If this is for the web application:
In order to show the label as soon as user opens the page.
You must write the code in page load.
Also If you want to display this Label only the first time and after that value changes over some event, then place the code as:
..Page_Load(..)
{
(!IsPostBack)
{
}
}
So that Label shows value first time page loads.
Any doubt you can ask again. :)
For window application logic remains the same.
private void label1_Click_1(object sender, EventArgs e) {}
call on Page Load like:
Page_Load(...)
{
label1_Click_1(null, null);
}

Couldn't get the values from the cells in GridView using check box in ASP.net

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
I have a button like this. But I'm not able to get the values of the cells(Label is not getting appended).
protected void Button1_Click(object sender, EventArgs e)
{
string[] FID={};
int j=0;
foreach (GridViewRow di in GridView1.Rows)
{
HtmlInputCheckBox chkBx = (HtmlInputCheckBox)di.FindControl("CheckBox1");
if ( chkBx != null && chkBx.Checked)
{
FID[j] += di.Cells[2].Text;
j++;
Label1.Text += di.Cells[2].Text;
//Label lbl = (Label)di.FindControl("Id");
//Response.Write(lbl.Text + "<br>");
}
}
}
Put your page load code under if(!IsPostBack){yourCode....} so when you click the button your page load event will be called before the click handler and it will rebind the gridview.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
}
i think if you can debug the code,
you can find and solve your problem easily.
First, check is your loop really do.
Second, is Cell[2] is really what you want to get data.(I doubt that)
Hope it works!

Categories

Resources