Update the data in database in asp.net - asp.net

I can successfully select the data I want to update to another page and populate my text boxes but if I set the selected values to my textbox and then try to update it wouldn't work and the same data is shown in database table.
However if I DO NOT set those values to my textboxes, then I can successfully update which is not what I am after.
I would like the user to see the data and record that s being updated
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
UserClassesDataContext db= new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
TextBox1.Text = q.user_name;
TextBox2.Text = q.password;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
UserClassesDataContext db = new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
q.user_name = TextBox1.Text;
q.password = TextBox2.Text;
}
db.SubmitChanges();
Response.Redirect("Default.aspx");
}
What am I doing wrong?
Thanks

The problem is, when you submit the button, the code inside Page_Load event is executing again.That means it is reading the data from your table and setting the value to textboxes(thus overwriting what user updated via the form ) and you are updating your record with this values (original values). So basically you are updating the rows with same values.
You can use the Page.IsPostBack property to determine whether the event is occurred by a postback(button click) or initial page load.
This should fix it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// to do: read and set to textbox here.
}
}

Related

unable to persist data on postback in dotnetnuke7

I have my website running on dotnetnuke 7.4, i have a checklistbox which i bind on the page load, and after selecting items from it, user clicks on the submit button, the selected items should save in database, however when i click on the submit button, checklistbox gets blank, i tried to enable ViewState at :
Web.config level
Page Level
Control Level
But all in vain, it still unbinds checklistbox because of which everything disappears, i tried the same in plain .net and it works like a charm.
Is there any specific settings in dotnetnuke to support viewstate, or is there any other better option to achieve this.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in chkBox.Items)
Response.Write(item.Text + "<br />");
}
There's the issue. Remove that (!IsPostBack) check in your page_load event. Have your code to be like below. Else, only at first page load you are binding the datasource to control which gets lost in postback.
protected void Page_Load(object sender, EventArgs e)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
OR, to be more efficient; refactor your code to a method like below and store the data object in Session variable like
private void GetDataSource()
{
List<Entities> obj = null;
if(Session["data"] != null)
{
obj = Session["data"] as List<Entities>;
}
else
{
Entities objEntities = new Entities();
obj = objEntities.GetList(2);
}
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
Session["data"] = obj;
}
Call the method in your Page_Load event like
protected void Page_Load(object sender, EventArgs e)
{
GetDataSource();
}

Write Cookies and set cookies value as text box select Vlaue

I am trying to store the selected value of a dropdown list in a cookies which work perfectly with this code.
protected void state_DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie StudentCookies = new HttpCookie("userloaction_cookies");
StudentCookies.Value = state_DropDownList.SelectedValue;
StudentCookies.Expires = DateTime.Now.AddDays(1000);
Response.Cookies.Add(StudentCookies);
}
I then want to use the cookie value to set the select value for the dropdown list after page_load. It works, but I cannot change the dropdown value after the first value has been stored in the cookies.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["userloaction_cookies"] != null)
{
HttpCookie aCookie = Request.Cookies["userloaction_cookies"];
string cookiesvalue = Server.HtmlEncode(aCookie.Value);
state_DropDownList.SelectedValue = Server.HtmlEncode(aCookie.Value);
}
I think the issue is that the Page_load method triggers before the state_DropDownList_SelectedIndexChanged method.
Is there any possible way of making this work?
Page load triggers first on each post back.
You will need to check the value of IsPostBack.
Here is how:
if (!IsPostBack)
{
if (Request.Cookies["userloaction_cookies"] != null)
{
HttpCookie aCookie = Request.Cookies["userloaction_cookies"];
string cookiesvalue = Server.HtmlEncode(aCookie.Value);
state_DropDownList.SelectedValue = Server.HtmlEncode(aCookie.Value);
}
}

asp.net textbox not updated from another task

I have a GridView and on its SelectedIndexChanged the code is fired:
protected void grdEntry_SelectedIndexChanged(object sender, EventArgs e)
{
lblAssignId.Text = grdEntry.SelectedRow.Cells[1].Text == " "
? ""
: grdEntry.SelectedRow.Cells[1].Text;
Ob.BranchId = Globals.BranchID;
Ob.AssignId = lblAssignId.Text;
DataSet dsMain = GetAssignDetails(Ob);
if (dsMain.Tables[0].Rows.Count != 0)
{
// some other code
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
}
}
and the code for filling membership id is
private void FillMemberShipAndBarCode(string customerCode, string branchId)
{
var sqlCommand = new SqlCommand
{
CommandText = "sp_customermaster",
CommandType = CommandType.StoredProcedure
};
sqlCommand.Parameters.AddWithValue("#CustomerCode", customerCode);
sqlCommand.Parameters.AddWithValue("#BranchId", branchId);
sqlCommand.Parameters.AddWithValue("#Flag", 18);
var data = PrjClass.GetData(sqlCommand);
txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
txtBarCode.Text = data.Tables[0].Rows[0]["Barcode"].ToString();
}
It's working fine, but is is not updating any of the textboxes. Also, I checked in watch window, the values are returned as expected (M-1213 and 634-98-4 ) and the code does reaches the point txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
but the txtMemberShip just remains empty??? Can anyone tell me why is not updating the textboxes?
UPDATE
As per comments, here is the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
BindGrid();
SetDefaultsInTextBoxes();
}
}
And I don't have any code that waits on this task.
Don't do this:
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
What are you trying to achieve by doing so?
What is probably happening is your method FillMemberShipAndBarCode is probably running after ASP.NET has already sent the page back to the browser. Thus, essentially, no visible effect on the rendered HTML.
ASP.NET isn't a good place to do multi-threaded stuff.
Try just replacing the above with this:
FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId);

Linq deferred execution in asp.net

My dbml contains a master table "M" and a detail table "D1".
My aspx page consists of a TextBox to show M data and a grid to populate with D1 data. I want the grid to populate when a button is clicked to save loading time (D1 contains a lot of rows).
Question 1: Is the following code the correct way to do it?
protected void Page_Load(object sender, EventArgs e)
{
MyDataContext context = new MyDataContext();
M m = context.Ms.Single(n => n.id == id); // id is somehow provided
TextBox1.Text = m.field1;
}
protected void Button1_Click(object sender, EventArgs e)
{
MyDataContext context = new MyDataContext();
M m = context.Ms.Single(n => n.id == id); // id is somehow provided
Grid1.DataSource = m.D1s;
Grid1.DataBind();
}
Question 2: Since I can access m.D1s in Page_Load does this mean the detail data is already fetched from the database anyway or does deferred execution apply?
Unless you explicitly load the children, they will be deferred loaded. If in question, try attaching a profiler to your requests and debug into the program to see when the queries are issued.
If you want to eager load the children in LINQ to SQL, use the LoadOptions with the LoadWith operation.
protected void Button1_Click(object sender, EventArgs e)
{
MyDataContext context = new MyDataContext();
var lo = new DataLoadOptions();
lo.LoadWith<M>(m => m.D1s);
context.LoadOptions = lo;
M m = context.Ms.Single(n => n.id == id); // id is somehow provided
Grid1.DataSource = m.D1s;
Grid1.DataBind();
}
In this case, if you don't need the m since it was already set in the page load, just load the appropriate D1s without reloading M in the button click handler:
protected void Button1_Click(object sender, EventArgs e)
{
using (MyDataContext context = new MyDataContext())
{
IQueryable<D> D = context.D1s.Where(d => d.Mid == id);
// id is somehow provided
Grid1.DataSource = D;
Grid1.DataBind();
}
}

Call a button_click on page_load asp.net

I have a search textbox and a search button, when clicked displays a grid with the following names and gender.However I have redirected the page to another page on edit.Now When I comeback from that page to the page containing the gridview I want to display the same search again. I have successfully put retrieved the information but storing it into session, but I'm not able to call my btn_click event # page_Load.
Here's a snippet:
EDIT: I have made some changes in my code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
if (Session["FirstName"] != null)
txtSearch.Text = Session["FirstName"].ToString();
if (Session["Gender"] != null)
ddlGen.SelectedValue = Session["Gender"].ToString();
btnSearch_Click(sender, e);
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
and here's the click event:
protected void btnSearch_Click(object sender, EventArgs e)
{
string query = "Select EmployeeId,FirstName,Password,Address,sex,Deptno,act_book,actTV,DOJ,isActiveYN from employees where 1=1";
if (txtSearch.Text != "")
{
query += " and FirstName like '%" + txtSearch.Text + "%'";
Session["FirstName"] = txtSearch.Text;
}
if (ddlGen.SelectedValue != "")
{
query += " and sex='" + ddlGen.SelectedValue.ToUpper() + "'";
Session["Gender"] = ddlGen.SelectedValue;
}
DataSet ds = new DataSet("Employees");
SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr");
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds);
gvSession.DataSource = ds;
gvSession.DataBind();
}
Now I'm able to save search, so that problem is resolved ,but another has poped up that when I click the button search after changin text it takes me back to the older search..The reason is probably because sessions are not cleared,but I did that as well by handling textchanged and selectedindexchanged eventd.
Rather than trying to call your button click handler from the Page_Load, change your button click handler to simply call another method like:
protected void btnSearch_Click(object sender, EventArgs e)
{
RunSearch();
}
Then move all your btnSearch_Click() code into RunSearch()
Then in your Page_Load you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Gender"] != null && Session["FirstName"] != null)
{
txtSearch.Text = Session["FirstName"].ToString();
ddlGen.SelectedValue = Session["Gender"].ToString();
RunSearch();
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
On a side note, I would recommend taking a look into SQLCommand Parameters. Your code is prone to SQL Injection Attacks:
http://en.wikipedia.org/wiki/SQL_injection
You should reset the session redirected variable so it doesn't fall in the same case.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
Session["Redirected"] = null;
....
You can do using an QueryString paremeter when page return back to main page then here you can check QueryString paremeter is exist. here you can implement code for bind grid
if (Request.QueryString["Back"]!= null)
{
// Your bind grid function
}
You can create a function, which will called both from the button_click and page_load.

Resources