When I enter new data and press update button it saves the old data (data that I want it to update).
public void fill()
{
SqlCommand cmd = new SqlCommand("select * from school ",con );
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
fill();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
string stu =((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
int age = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
SqlCommand cmd = new SqlCommand("UPDATE school SET stu_name=#stu_name,age=#age where id=#id ", con);
cmd.Parameters.Add(new SqlParameter("#id", id));
cmd.Parameters.Add(new SqlParameter("#stu_name", stu));
cmd.Parameters.Add(new SqlParameter ("#age",age));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fill();
}
he problem that the values that assigned to name,age are the existing values in the database not the new values which I entered in the runtime
any one can help me??
thanks in advance
You are repopulating the grid every time you edit it.
Call fill(); on grid init instead.
Here's some info on the Life Cycle of a web form. I think all you need is to wrap your fill(); in an if statement. Because page_load happens before your event handler, you reload from the db on top of the values that were entered.
if(!PostBack)
{
fill();
}
Related
After I get the value show in GridView the DropDownList will contain duplicate items when I click again.
public void Page_Load(object sender, EventArgs e)
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
public void button_click(object sender, EventArgs e)
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
You should write it as:
public void Page_Load
{
if (!IsPostBack){
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
}
public void button_click
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
The Page_Load method is called each time a postback occurs (such as when you click on an ASP.NET button control). The data was already added on the first load and stored in ViewState. On the second request, it adds it again. You can detect whether you're in a postback by using the Page.IsPostBack property.
public void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// add items to drop down list
}
}
Side note, make sure that any objects that implement the IDisposable interface are handled properly. You need to make sure they're disposed when you're done with them to avoid hard to diagnose errors. You can either call .Dispose() on them in a finally block or you can wrap them in a using statement. Your SqlCommand, SqlConnection (this should not be a property/field)andSqlDataReaderall implementIDisposable`.
I just found the solution. Put the if(!Ispostback) in the page load statement there.
At best-guess, without compile-able code, it looks like your Dropdown List is persisted between page loads, meaning it's never going out of context (the object remains in memory). So, it is just getting appended over and over each time there is a page load. You probably want to do a check for existing values:
public void Page_Load()
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
using(SqlCommand cmd = new SqlCommand(sql, con)) {
using(SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
//Have not tested the if statement... may need to correct it.
if(!DropDownList1.Items.Contains(dr[0].ToString())) {
DropDownList1.Items.Add(dr[0].ToString());
}
}
}
}
con.Close();
}
I have a grid view in which there is functionality to update/delete rows. I am storing the data to SQL using stored procedure. When I click on Edit button and change the existing value and after clicking Update button I am getting old values.
My code is :
protected void grdNatureFormation_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
ConnectionString = GetConnectionString();
LinkButton link = (LinkButton)grdNatureFormation.Rows[e.RowIndex].FindControl("btnUpdate");
int id = Convert.ToInt32(link.CommandArgument);
TextBox title = (TextBox)grdNatureFormation.Rows[e.RowIndex].FindControl("txtTitle");
if(title != null)
{
using (SqlConnection Sqlcon = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
Sqlcon.Open();
cmd.Connection = Sqlcon;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "NatureOfFormation";
cmd.Parameters.Add(new SqlParameter("#ID", SqlDbType.Int)).Value = id;
cmd.Parameters.Add(new SqlParameter("#Title", SqlDbType.VarChar)).Value = title.Text.Trim();
cmd.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar)).Value = "update";
cmd.ExecuteNonQuery();
grdNatureFormation.EditIndex = -1;
LoadData();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
ConnectionString = GeneralMethods.GetConnectionString();
SqlConnection Sqlcon = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
try
{
Sqlcon.Open();
cmd.Connection = Sqlcon;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "xxx";
cmd.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar, 50));
cmd.Parameters["#Action"].Value = "select";
SqlAda = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlAda.Fill(ds);
grdNatureFormation.DataSource = ds;
grdNatureFormation.DataBind();
}
catch
{
}
finally
{
if (Sqlcon.State == ConnectionState.Open)
Sqlcon.Close();
Sqlcon.Dispose();
cmd.Dispose();
}
}
I searched over internet for the issue and most of the posts suggest to place the data binding method in the (!Page.IsPostBack) , but in my case it is already in the same condition but not getting value.
What should I do to get new value in RowUpdating event?
RowUpdating is called before the gridview values are updated. You need to put your code into the RowUpdated event handler.
For more info, see the manual: GridView Events
RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control updates the row.
RowUpdated - Occurs when a row's Update button is clicked, but after the GridView control updates the row.
I am trying to delete record from grid but not from Database.
I want to set database field ISDeleted 1 when data deleted from gridview but don't want to delete record from db.
My code delete records from both gridview and db.
Where to change in my code-
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//GridView1.DataBind();
if (!Page.IsPostBack)
{
fillLanguageGrid();
}
}
public void fillLanguageGrid()
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chk");
if (chkdelete.Checked)
{
string name= Convert.ToString(GridView1.DataKeys[gvrow.RowIndex].Values["Name"].ToString());
// command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
deleteRecordByName(name);
}
}
fillLanguageGrid();
}
public void deleteRecordByName(string Name)
{
SqlConnection sqlConnection = new SqlConnection(strcon);
using (SqlCommand command = new SqlCommand("[dbo].[hrm_Langauges]", sqlConnection))
{
// define this to be a stored procedure
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
// define the parameter and set its value
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#IsDeleted", SqlDbType.Bit)).Value = 1;
command.Parameters["#status"].Value = "Delete";
//open connection, execute DELETE query, close connection
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Dispose();
}
}
For that you need to add a column in your respective database table whether to show that record or not.For Ex: add column like Visible int.
Assume if
Visible =1 --> Show that record in gridview
Visible =0 --> Hide that record in gridview
By default make Visible =1 so all records are shown in gridview(write the query like Select ......Where Visible =1).when you try to delete record use update query that need to update Visible column 1 to 0.So your gridview only shows records where visible =1 .That particular deleted record is not shown in your gridview because its Visible column is 0.Try this..
I have a problem : I have page for insert data into database , and the same page for update data based on query string for each item , the problem when i update the fields from textbox(s) , the same data is returned to update: the same data updated in database from textbox in page_load !!
In Page_Load
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
protected void Btn_addItem_Click(object sender, EventArgs e)
{
if (Btn_addItem.Text.Equals("Add Item"))
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", "-1");
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item added....";
con.Close();
}
else
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", Request.QueryString["id"]);
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item edited....";
con.Close();
}
}
If I understand your question correctly "You are not able to update the DB with the new value you enter in the textboxes. Its updating the DB with the old value again".
You need to check for !IsPostback in your Page_Load as the code for binding the textboxes from DB will be called before Btn_addItem_Click during postback and it will set the value of textboxes back to the old value from DB. See below updated code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
}
}
Hope it helps.
i have two text-boxes a button and a gridview.
Q.1 When user enter details in the text-boxes and press submit button i want to update grid-view accordingly
Q.2 When user hits "Edit" link which is present in the gridview, i would like to change the text of submit button to Update button.
how can i do that thanks in advance
what i have tried yet:
aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
string ID = Request.QueryString["ID"];
cmd = new SqlCommand("Select * from UserDetails where ID='" + ID + "'", con);
con.Open();
ad = new SqlDataAdapter(cmd);
dt.Clear();
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
tbid.Text = ID;
TextBox1.Text = dt.Rows[0][1].ToString();
TextBox2.Text = dt.Rows[0][2].ToString();
}
con.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
con.Open();
string Name = TextBox1.Text;
string Place = TextBox2.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into UserDetails(Name,Place) values('" + Name + "','" + Place + "')";
cmd.Parameters.AddWithValue("#Name", TextBox1.Text);
cmd.Parameters.AddWithValue("#Place", TextBox2.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Record Successfully inserted";
}
con.Close();
btnSubmit.Text = "Update";
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
private void BindGrid()
{
con.Open();
ad = new SqlDataAdapter("Select * from UserDetails", con);
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Call a Refresh() doesn't help? I'm not sure about ASP.NET, but you have to do it in Forms.
After the user submits new data you can try to call your bindgrid method again, this way it will rebind after the new data is saved. For the edit piece, GridView has an edit template, you can try using that:
http://msdn.microsoft.com/en-us/library/ms972948.aspx