IsPostBack doesn't work in ASP.NET - asp.net

I want that when the page is first loaded , the string str is initialized with the text "I am here". And when the page is updated by clicking on the button (btn_click) the value is the same that was initialized. But it does not work. In the console I reads:
First time I load the page: "I ​​am here"
1.When I click on the button: "empty"
2.And I think we should keep this value: "I am here". Please help.
public partial class Default : System.Web.UI.Page
{
string str = "empty";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
str = "I am here";
Debug.Write("VALUE: " + str + "\r\n");
}
else
{
Debug.Write("VALUE: " + str + "\r\n");
}
}
protected void btn_Click(object sender, EventArgs e)
{
//do something...
}
}

Each individual request to the server creates a new instance of the page... both the very first request (IsPostBack==false) and all subsequent requests (IsPostBack==true).
This means that your str variable is initialised with "empty" every time you request the page, but only ever set to "I am here" on the first load (i.e. the IsPostBack==false). You need to store it somehow so that when the post-back occurs you still have it.
There are several ways, including using the Session object, but I would suggest using the ViewState like this...
string str = "empty";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
str = "I am here";
ViewState["str"] = str;
Debug.Write("VALUE: " + str + "\r\n");
}
else
{
str = (string)ViewState["str"];
Debug.Write("VALUE: " + str + "\r\n");
}
}

Related

Null after onClick action

I'm starting with asp.net, but i'm not quite sure what am I doing wrong. Actually my first step in asp is to make a calculator but after 2h of looking for answer i've decided to ask you about that.
I have 10 buttons with [0,1,2...9], 4 action buttons [+,-,*,/] and one button to calculate [=]:
int firstNumber, secondNumber;
Button lastClicked;
bool isFirstNumberSet;
protected void Page_Load(object sender, EventArgs e)
{
firstNumber = 0;
isFirstNumberSet = false;
lastClicked = new Button();
}
public void addToTextbox(object sender, EventArgs e)
{
Button number = (Button)sender;
TextBox1.Text += number.Text;
}
public void doSomething(object sender, EventArgs e)
{
if (isFirstNumberSet.Equals(false)) firstNumber = int.Parse(TextBox1.Text);
else secondNumber = int.Parse(TextBox1.Text);
lastClicked = new Button();
lastClicked = (Button)sender;
isFirstNumberSet = true;
TextBox1.Text = "";
}
public void calculate(object sender, EventArgs e)
{
switch (lastClicked.ID)
{
case "ButtonPlus":
TextBox1.Text = (firstNumber + secondNumber).ToString();
isFirstNumberSet = false;
break;
case "ButtonMinus":
TextBox1.Text = (firstNumber - secondNumber).ToString();
isFirstNumberSet = false;
break;
case "ButtonDziel":
TextBox1.Text = (firstNumber / secondNumber).ToString();
isFirstNumberSet = false;
break;
case "ButtonMnoz":
TextBox1.Text = (firstNumber * secondNumber).ToString();
isFirstNumberSet = false;
break;
}
but when i do for example action like 2 + 2, and after that i hit "=". I get an exception about that code:
switch (lastClicked.ID)
It says that lastClicked is null, but how? after hit "+" this should save sender object to this variable. Am i wrong?
Your button variable assignment does not persist between postbacks the way you are expecting. When calculate fires upon your "=" keyhit, lastClicked is now unassigned on this new "round trip," and thus null. When you press one button once, then a second button the next time, there's no memory of the previous hit unless you store the value in a field that's captured in the data sent back to the server.
One approach you could explore involves storing the operation that's been selected into a hidden HTML field on your form, and then interrogate that upon hitting the calculate routine. That eliminates the need to try persisting the "lastClicked" button as you have.
Somewhere in your aspx, within your form, you could add:
<asp:HiddenField id="Operation" runat="server" />
Then, in your codebehind in response to one of your operator buttons:
Operation.Value = "Plus"; // or "+" or whatever is appropriate
That would then get sent back down to the client on the next trip, and then be part of the data sent back to the server when your calculate method is called in response to the "=" button click:
public void calculate(object sender, EventArgs e){
switch(Operation.Value){
case "Plus";
// do the "PLUS" thing
// and so on
... (snip)...
}

Replace NULL in querystring asp.net

I have a Response.Redirect on a buttonclick with two querystring-parameters that hold the value from two textboxes. If I leave the textboxes empty I get this URL: /Order.aspx?LastName=&FirstName=. I want to replace the NULL value with "%20" like this /Order.aspx?LastName=%20&FirstName=%20.
Please help my with the if-statements to changes this, I'm really new to this. Here is my code:
protected void btnSearchFirstLastName_Click(object sender, EventArgs e)
{
Response.Redirect("~/Order.aspx?LastName=" + SearchLastName.Text.Trim() + "&FirstName=" + SearchFirstName.Text.Trim());
}
Check string using string.IsNullOrEmpty, if true then set something of your choice like " " or string.Empty.
protected void btnSearchFirstLastName_Click(object sender, EventArgs e)
{
Response.Redirect("~/Order.aspx?LastName="
+ string.IsNullOrEmpty(SearchLastName.Text) ? " ": SearchLastName.Text.Trim()
+ "&FirstName=" + string.IsNullOrEmpty(SearchFirstName.Text) ? " " : SearchFirstName.Text.Trim());
}
protected void btnSearchFirstLastName_Click(object sender, EventArgs e)
{
string firstName = "%20";
string lastName = "%20";
if (!string.IsNullOrWhitespace(SearchFirstName.Text)
firstName = SearchFirstName.Text.Trim();
if (!string.IsNullOrWhitespace(SearchLastName.Text)
lastName = SearchLastName.Text.Trim();
Response.Redirect("~/Order.aspx?LastName=" + lastName + "&FirstName=" + firstName);
}
I think you can simply add this condition that if textbox is empty, then text should be as mentioned by you.
Like:
If(abc.text!=string.empty || abc.text!=null)
{
param value=abc.text;
}
else
param value="%20";
Note: This is a side option, you can opt if coding paradigms is not a concern here.

How can I display User Input to another page

How can I display user input if I have this example.
(Default.aspx)
FirstName: (textbox)
Last Name: (textbox)
I wanted to display the user input coming from Default.aspx to another page (WebForm1.aspx)
using Response.Redirect.
How can I do this ?
Is
Response.Redirect("WebForm1.aspx?VariableName" + TextBox1.Text)
and TextBox1.Text.Request.QueryString("VariableName")
working ?
Yes, it will work but you need to add = after your variable name as below
Response.Redirect("WebForm1.aspx?VariableName1=" + TextBox1.Text + "&VariableName2="+ TextBox2.Text);
and also in yourWebForm1.aspx
TextBox1.Text = Request.QueryString["VariableName"];
TextBox2.Text = Request.QueryString["VariableName2"];
Page one:
protected void Button1_Click(object sender, EventArgs e)
{
String strTxt1 = TextBox1.Text.ToString();
String strTxt2 = TextBox2.Text.ToString();
Response.Redirect("~/new_name.aspx?fName=" + strTxt1 + "&lName=" + strTxt2);
}
Page two:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Request.QueryString["fName"].ToString();
Label2.Text = Request.QueryString["lName"].ToString();
}

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.

Send data through the QueryString with ASP.NET

I want to send a string to another page named Reply.aspx using the QueryString.
I wrote this code on first page that must send the text to Reply.aspx:
protected void FReplybtn_Click(object sender, EventArgs e)
{
String s = "Reply.aspx?";
s += "Subject=" + FSubjectlbl.Text.ToString();
Response.Redirect(s);
}
I wrote this code on the Reply.aspx page:
RSubjectlbl.Text += Request.QueryString["Subject"];
But this approach isn't working correctly and doesn't show the text.
What should I do to solve this?
Thanks
Though your code should work fine, even if the source string has spaces etc. it should return something when you access query string, please try this also:
protected void FReplybtn_Click(object sender, EventArgs e)
{
String s = Page.ResolveClientUrl("~/ADMIN/Reply.aspx");
s += "?Subject=" + Server.UrlEncode(FSubjectlbl.Text.ToString());
Response.Redirect(s);
}
EDIT:-
void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString.HasKeys())
{
if(!string.IsNullOrEmpty(Request.QueryString["Subject"]))
{
RSubjectlbl.Text += Server.UrlDecode(Request.QueryString["Subject"]);
}
}
}
PS:- Server.UrlEncode is also sugested in comment to this question.
this is easy :
First page :
string s = "~/ADMIN/Reply.aspx?";
s += "Subject=" + FSubjectlbl.Text;
Response.Redirect(s);
Second page :
RSubjectlbl.Text = Request.QueryString["Subject"];

Resources