I have error in updating records in database sql server - asp.net

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.

Related

how to add confirmation in if statement

In my gridview I am inserting datas. If items repeated then it will show error message that "item repeated".But now I need to show "item repeated" message and another message that "you need to insert this data". If user press yes then that data need to be inserted.My current code only displays item repeated and cannot permit that data to enter. Here is my code
protected void AddNewCustomer(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string SlNo = (control.FindControl("txtSlNo") as TextBox).Text;
string Code = (control.FindControl("txtcode") as TextBox).Text;
string details = (control.FindControl("txtdetails") as TextBox).Text;
string Qty = (control.FindControl("txtqty") as TextBox).Text;
using (SqlConnection con = new SqlConnection("Data Source=xxxxx;Initial Catalog=xxxxx;User ID=xxxxx;Password=xxxxxx"))
{
using (SqlCommand cmd = new SqlCommand())
{
DataTable dt = new DataTable();
SqlDataAdapter da1;
da1 = new SqlDataAdapter("select code from Qtattemp where code='" + Code + "' ", con);
da1.Fill(dt);
if (dt.Rows.Count > 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Item Repeated');", true);
}
else
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [Qtattemp] VALUES(#Code,#details,#Qty,#SlNo)";
cmd.Parameters.AddWithValue("#SlNo", SlNo);
cmd.Parameters.AddWithValue("#Code", Code);
cmd.Parameters.AddWithValue("#details", details);
cmd.Parameters.AddWithValue("#Qty", Qty);
con.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
BindData();
con.Close();
}
}
}
}
You need to handle it from code behind see the following link
http://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx

GridView_RowUpdating returning old values

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.

Gridview does not view the results in asp.net

I am trying to show the search results on a gridview on the same search page in asp.net. Here is the UI:
And here is my code:
protected void Page_Load(object sender, EventArgs e)
{
searchResults.DataBind();
}
protected void BClassSearch_Click(object sender, EventArgs e)
{
// if (!IsPostBack)
//{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string selected = lbCourseListBox.SelectedValue;
if(selected!="" && Tcoursenumber.Text!="")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue+"' and CourseNumber = '" + Tcoursenumber.Text+"'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
else if (selected != "" && Tcoursenumber.Text == "")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue;
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
else if (selected == "" && Tcoursenumber.Text != "")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseNumber='" + Tcoursenumber.Text;
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
//}
Response.Redirect("SearchCourse.aspx");
}
The problem is, no search result is displayed in gridview. Can anyone help me with this?
Thanks
Remove Response.Redirect("SearchCourse.aspx"); at the end of button click
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do you want to bind something in first time load? then load it here
// searchResults.DataSource = tab;
searchResults.DataBind();
}
}
You don't want to call the Response.Redirect to the same page because when you click on button it will postback the page. if you call Response.Redirect it will load new page and you will lost all the control states in the page.

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

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

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;
}

Resources