I want my controls value.Insert only one time when I click the button - asp.net

I have a DropDownlist and a textbox in my page, when I click the button,Button1_Click event fire and get the value od textbox and droppdownlist and send them to my table in database and it shows me the result(new added row in my table in database) in gridview.
my problem is after I click the button if I refresh my page I mean click on reload Current page ,my dropdownlist value and textbox value insert again in my table .
I don't know how solve it?
my gridview use sqldatasource and this is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int brandid = Convert.ToInt32(BrandDropDownList.SelectedValue);
String catname = TextBox2.Text;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "FirstInitialiseCategories";
cmd.Parameters.AddWithValue("#brandid ", brandid);
cmd.Parameters.AddWithValue("#catname ", catname);
try
{
cn.Open();
cmd.ExecuteNonQuery();
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "با موفقیت ثبت شد!";
SqlDataSource2.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "خطا در ثبت!";
}
finally
{ cn.Close(); }
}

You can do a HTTP redirect (to the same page) once you're done with your first insert, it should solve the issue:
Response.Redirect("samePage.aspx");

what is the first item in your dropdown list? you could set a null value to the first item and when you inserted value to database, you can add code to clear the text box and drop down list.
finally
{
cn.Close();
Label1.Text ="";
ddl.SelectedIndex = 0;
}

Related

GridView RowCommand update send variable to javascript function

I have a Gridview that has an update link on it. Once "Edit" is selected from one of the rows the values in that row in the grid change into text boxes and can be edited. The "edit" button disappears and changes into an "update" link. Then the user edits the contents of one (or more than one) of the text boxes and "update" is selected. A JavaScript confirmation box appears asking if the user wants to update the values(s) and the changes are saved or discarded depending upon the choice selected. This is performed by "OnClientClick"
However I want to validate the change server side and pass back a defined error message to the user if the validation has failed. Example; if registered company name in the wrong format has been entered into one of the text boxes in the row selected.
The grid row will then remain in an editable state until the user corrects the error. The operation can be discarded by selecting "Cancel" from the grid row (I already have this functionality).
The C# rowcommand function is:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
}
The ASPX is
<asp:LinkButton ID="lnkUpdate" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnClientClick="return ConfirmOnUpdate();" CommandName="Update" > Update</span></asp:LinkButton>
The javascript is
function ConfirmOnUpdate()
{
if (confirm("Are you sure you want to update this record?"))
return true;
else
return false;
}
Thank you for any replies
Use this code for handling server side validation.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
if (myTextBox_registered_company_name.Text != "") // add your validation in this if block, now it checks textbox is not empty;
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
else
{
ScriptManager.RegisterStartupScript(this,this.GetType(),"Error Message", "alert('TextBox is empty!')",true);
}
}

I have error in updating records in database sql server

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.

In DropDown Selected_Indexchanged event SelectedValue is always getting reset in First Value

I have DropdownList which I populate at the time of Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select distinct sname from contacts where sname is not null";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
DropDownList2.DataSource = table;
DropDownList2.DataValueField = "sname";
DropDownList2.DataTextField = "sname";
DropDownList2.DataBind();
}
}
Now I am trying to populate a GridView when the DropDownList's Item changes
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string val = DropDownList2.SelectedValue;
string sqlQuery = "SELECT distinct DUTY_DATE FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE and SYSDATE+30 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL and contacts.sname = '" + val + "' ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
I have enabled the AutoPostBack. Now when I am changing a DropDownList item to a different one the Page is loading but always retaining the first value. I tried to debug , I found that
string val = DropDownList2.SelectedValue;
the val variable is always the first value that is returned by the Query. Can anybody please tell me how could I get rid of this. I want to populate the GridView whenever I am selecting any item in the dropdown.
Hi i think that dropdownlist charge again when you select other item. Put a Break Point in Page Load and look if your dropdownlist charge again i don't see other reason. Good Luck
Your Drop downlist should look like as following :
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
Make sure AutoPostBack is Set to TRUE.
One more thing you can try is to select the item when the index is greater than -1.
if(DropDownList2.SelectedIndex != -1)
{
string val = DropDownList2.SelectedItem.Value;
// enter code here
}

how can i change the text on button at run time after click on hyperlink

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

DetailsviewInside Linkbutton onclick it rediects and open newtab

I am working with Details view inside details view Itemtemplete i have link button when click that link button it need to redirect and open new tab for that i use this code
protected void lnkPost_Click(object sender, EventArgs e)
{
DetailsViewRow row= (DetailsViewRow)((LinkButton)sender).NamingContainer;
int postID = Convert.ToInt32((row.FindControl("lblPostID") as Label).Text);
if (postID != null)
{
string Query = "Select * from GigPost where GigPostID='" + postID + "'";
SqlCommand cmd = new SqlCommand(Query, cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
string Postsource = dr["PostSource"].ToString();
Response.Write("<script> window.open('"+ Postsource+"' ); </script>");
Response.End();
}
}
}
I am getting "Unable to cast object of type 'System.Web.UI.WebControls.DetailsView' to type 'System.Web.UI.WebControls.DetailsViewRow'." this error please help me how to resolve this issue
Regards,
Venkat
DetailsViewRow row = (DetailsViewRow)(((LinkButton)sender).NamingContainer);
may work - (untested)
But really - what's wrong with using the ItemCommand of the DetailsView and grab the current datakey?

Resources