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.
Related
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.
}
}
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();
}
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);
}
}
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);
I have problem in updating user profile through asp:TextBox.
At the time of page load , all the textboxes get loaded with correct values from the database sqlserver.
say First name=SAM {i.e SAM is shown in txtName's textfield)
and Last Name=Berton
but when i alter the content of txtName to SAMANTHA
and similary for other textboxes, and click on update profile button, Internally txtName.text="SAM" gets retained notwithstanding the changed content of txtName.text="SAMANTHA" by manually altering the content of textbox.So same value that is "SAM" gets stored into the sqlserver rather than "SAMANTHA".
protected void Page_Load(object sender, EventArgs e)
{
loadProfileData();
}
protected void loadProfileData()
{
string connStringProfileload = ConfigurationManager.ConnectionStrings["myconnString"].ConnectionString;
SqlConnection conProfLoad = new SqlConnection(connStringProfileload);
conProfLoad.Open();
string emailAddLogin = User.Identity.Name.ToString();
string strSqlProfileLoad = "SELECT * FROM [gen_profile] WHERE [email]=#email";
SqlCommand cmd = new SqlCommand(strSqlProfileLoad, conProfLoad);
cmd.Parameters.AddWithValue("#email", emailAddLogin);
SqlDataReader drProfileLoad = cmd.ExecuteReader();
while (drProfileLoad.Read())
{
txtName.Text = drProfileLoad["fname"].ToString();
txtLastName.Text=drProfileLoad["lname"].ToString();
}
drProfileLoad.Close();
conProfLoad.Close();
}
protected void BtnUpdtProf_Click(object sender, EventArgs e)
{
string connStringProfileUpdate = ConfigurationManager.ConnectionStrings["myconnString"].ConnectionString;
SqlConnection conUpdateProf = new SqlConnection(connStringProfileUpdate);
conUpdateProf.Open();
string emailAddLogin = User.Identity.Name.ToString();
string strSqlUpdateProf = "UPDATE gen_profile SET fname =#fname, lname =#lname where email=#email;";
SqlCommand cmdUpdate = new SqlCommand(strSqlUpdateProf, conUpdateProf);
cmdUpdate.Parameters.AddWithValue("#fname", txtName.Text.ToUpper().Trim());
cmdUpdate.Parameters.AddWithValue("#lname", txtLastName.Text.ToUpper().Trim());
cmdUpdate.Parameters.AddWithValue("#email", emailAddLogin);
int i = cmdUpdate.ExecuteNonQuery();
conUpdateProf.Close();
if (i == 1)
Response.Redirect("~/prof/resp_update_prof.aspx");
}
Change this method :
protected void Page_Load(object sender, EventArgs e) {
loadProfileData();
}
to :
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) loadProfileData();
}
Basically, your textBox values are being reset in the page load event, so everytime your page posts back, it's resetting the values in the textboxes and then saving them back to the database.
This is because before your button click event, page_load get's fired which re-populates the textbox.
You can stop this happening by checking for a post back as follows:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
{
loadProfileData();
}
}