Update button keeps updating on click of Refresh in IE - c#

I have a form wherein I populate content using stored procedure and I perform update actions on the content. Now my update button works fine. My problem is that each time I click on 'refresh' button in IE, the content gets updated and I don't want that to happen. I am new to .Net and all this ViewState stuff. Any help is appreciated..
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void BindGridView()
{
string constring = ConfigurationManager
.ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("spd_pc", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.Add("#city", SqlDbType.VarChar).Value = txt_city.Text;
con.Open();
IDataReader idr = cmd.ExecuteReader();
GridView1.DataSource = idr;
GridView1.DataBind();
idr.Close();
con.Close();
}
}
}
protected void Button1_click(object sender, EventArgs e)
{
BindGridView();
}
private void DeleteRecords(int id)
{
string constring = ConfigurationManager.
ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("del_pc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
CheckBox chkb = (CheckBox)row.FindControl("CheckBox1");
if (chkb.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
if (!(id.Equals(System.DBNull.Value)))
{
DeleteRecords(id);
}
}
}
BindGridView();
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!IsCallback)
{
string active = "active";
string inactive = "inactive";
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkb = (CheckBox)row.FindControl("CheckBox1");
if (chkb.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
string status = row.Cells[5].Text;
if (!(id.Equals(System.DBNull.Value)))
{
if ((String.Equals(active, status)))
UpdateRecords(id);
if ((String.Equals(inactive, status)))
UpdateRecords(id);
}
}
}
}
}
private void UpdateRecords(int id)
{
string constring = ConfigurationManager.
ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("upd_pc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
cmd.ExecuteNonQuery();
conn.Close();
}
}
BindGridView();
}
}

yes, this will happen. the problem is you are refreshing the post event of the button click. the solution is to redirect back to page after the update is complete.
button_click(...)
{
//save to db
Response.Redirect(Request.Referrer);
}
or something like that.
Now if the user clicks refresh it will submit the GET request to load the page, rather the POST to issue the button click event.
If you search for Post Get Redirect (or something like that) you will find lots of articles on the topic. describing both the situation you encountered and why this solution works.

Related

Dynamically add headers and columns to GridView

I have a gridview but currently it only sets one header. What I want it to do is add new header beside the other columns at the end of the table based on the number of users.
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView1.UseAccessibleHeader = true;
GridView1.AutoGenerateColumns = false;
int i = 6;
string constr = ConfigurationManager.ConnectionStrings["CMT"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM [user]";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
GridView1.Columns[6].HeaderText = sdr["user_first_name"].ToString();
break;
}
}
conn.Close();
}
}
}
}
You can add TemplateField columns to the GridView before binding the data. It could be done in the Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM [user]";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
TemplateField field = new TemplateField();
field.HeaderText = sdr["user_first_name"].ToString();
field.HeaderStyle.Width = Unit.Pixel(80);
GridView1.Columns.Add(field);
}
}
conn.Close();
}
}
}
}

How to remove subcategory in recursive function? asp.net

I am trying to delete subcategory from repeater using a link button. Currently, main category deleted but i cant delete subcaegory. Help me please...
private void BindRepeater()
{
DataTable dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID="+CategoryID);
if (dtCategory.Rows.Count > 0)
{
rpCategory.DataSource = dtCategory;
rpCategory.DataBind();
}
}
protected void OnDelete(object sender, EventArgs e)
{
//Find the reference of the Repeater Item.
RepeaterItem item = (sender as LinkButton).Parent as RepeaterItem;
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("Delete from TBLCATEGORIES where SubCategoryID="+CategoryID);
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DeleteMsg.Visible = true;
}
}
this.BindRepeater();
}
Please find the code,hope this will help you:
protected void rpCategory_ItemCommand(object source, RepeaterCommandEventArgs e)
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["ShqiptarConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
conn.Open();
if (e.CommandName == "Delete")
{
comm = new SqlCommand("Delete from TBLCATEGORIES where CategoryID=" + e.CommandArgument, conn);
comm.ExecuteNonQuery();
}
conn.Close();
conn.Dispose();
DeleteMsg.Visible = true;
//Rebind here: this.BindRepeater();
}

Attempting to get a count of records from gridview based on a selected date from dropdownlist but cant?

The problem lies that upon selection of the date in the dropdown it will give the count of the LAST selection, not the current.
I am a novice and the only thing I can think of is some type of postback issue? The gridview populates fine with the records selected by the DDL, so I just cant get my head around why the count that is rendered is the previous selection.
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e)
{
lblRecordCounter.Text = "";
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT (*) FROM gescdb" +
"WHERE ClassDate=" + ddlClassDate.Text, conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
GridRegistrants.DataSource = reader;
GridRegistrants.DataBind();
reader.Close();
}
catch
{
}
finally
{
conn.Close();
lblRecordCounter.Text = GridRegistrants.Rows.Count.ToString();
}
In your Page_Load method you do the same, right? You have to move that code into following block:
if (!IsPostBack){
//Your code is here
}
Your DropDownList:
<asp:DropDownList ID="ddlClassDate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlClassDate_SelectedIndexChanged" />
Your code behind:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
BindDDL();
BindGrid(ddlClassDate.SelectedValue);
}
}
protected void BindDDL(){
//Bind Your dropdownlist here
}
protected void BindGrid(string ddate){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString);
SqlCommand comm = new SqlCommand("select * from gescdb where ClassDate = #date", conn);
comm.Parameters.Add("#date", SqlDbType.VarChar).Value = ddate;
try
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
GridRegistrants.DataSource = ds;
GridRegistrants.DataBind();
}
catch
{
//...
}
finally
{
conn.Close();
}
}
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e){
BindGrid(ddlClassDate.SelectedValue);
}

update asp.net text box

I have problem with updating data.
Sample:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[1].Text;
Response.Redirect("edit.aspx?id="+id);
}
after this code transition to another page with update cmd.
protected void Page_Load(object sender, EventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
con.Open();
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.ExecuteNonQuery();
Response.Redirect("main.aspx");
}
I clicked button, and was redirected to main page. But nothing else, update doesn't work. :(
where do I have a problem?
I don't really know where is the problem, but for sure you need to refactor your update statement using the IDisposable capabilities of the connection object, it shoul look like this:
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString))
{
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, connection);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
Your update sql query looks fine:
con.Open();
com.ExecuteNonQuery();
con.Close();
that is try using this function instead and debug it to see if there is a sql exception thrown.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("main.aspx");
}
catch (SqlException e)
{
}
}
UPDATE: Think I've realised why it's not working for you... you have a column called class... but class in sql server is a reserved keyword... so you must put square brackets around it ... like so
Edited the escaping (made a mistake as pointed out by Hans in the comment below)
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, [Class]=#Class WHERE ID=#ID";
The problem was found.Just add in Page_Load if(!isPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
Now, all working good.

Data doesn't get updated when an item is chosen from drop down list

I would like ask if you could help me with my codes as I don't get the result that I want which is to load the details of a particular paper from drop down list.
Currently, when the page loads, the details of the selected item will load up. But when I try to choose another item from the drop down list, corresponding details won't show up, the previous one still remains instead.
Under the properties of drop down list, I also set autopostback to yes so that it will automatically load the corresponding details of the item selected.
Please see codes below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPaper();
GetInk();
GetPaperDetails(ddlPaperName.SelectedItem.Value);
//pnlPrinting.Visible = true;
}
}
protected void btnCompute_Click(object sender, EventArgs e)
{
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
private void GetPaper()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "PaperID";
ddlPaperName.DataTextField = "PaperName";
ddlPaperName.DataBind();
data.Close();
con.Close();
}
private void GetPaperDetails(string paper)
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers WHERE PaperID=" + paper;
SqlDataReader data = com.ExecuteReader();
while (data.Read())
{
lblPaperPrice.Text = data["PaperPrice"].ToString();
lblDescription.Text = data["PaperDescription"].ToString();
lblSpecification.Text = data["PaperSpecification"].ToString();
imgPaper.ImageUrl = "../" + data["PaperImage"].ToString();
}
data.Close();
con.Close();
}
private void GetInk()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Inks";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "InkID";
ddlPaperName.DataTextField = "InkName";
ddlPaperName.DataBind();
while (data.Read())
{
lblInkPrice.Text = data["InkPrice"].ToString();
}
data.Close();
con.Close();
}
protected void ddlPaperName_SelectedIndexChanged(object sender, EventArgs e)
{
GetPaperDetails(ddlPaperName.SelectedItem.Value);
}
Looking forward to your feedback here. Thanks!
Set AutoPostBack property to true of your drop down list.
us this code, for that,
if (!IsPostBack == true)
{
drpdownaccountnamebind();
drpdowncountrynamebind();
}
i hope this will be helpful,

Categories

Resources