I'm learning ASP.NET and I don't understand what is going on here.
The code behind file:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Some more text";
TextBox1.ForColor = System.Drawing.Color.Blue;
}
Essentially all there is just a label that tells you what the color and text of the textbox is. When you hit the button it changes the color to blue, and the page reloads.
Why is it that when you press the button the first time and the page reloads, the label does not update to the correct information? You have to press the button again for it to read that the text box is red.
Can anyone provide an explanation for this behavior? And how to change the Page_Load method to fix this issue?
The Page_Load event is being handled before the control events. See the description of the page lifecycle at http://msdn.microsoft.com/en-us/library/ms178472.aspx. To fix it, modify the code so that both Page_Load and the Button_Click handlers call the same method to set the label value. Only have Page_Load execute if the method isn't a POSTBACK.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetUpLabel();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Some more text";
TextBox1.ForeColor = System.Drawing.Color.Blue;
SetUpLabel();
}
private void SetUpLabel()
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
You Need To Write The Code In Page_Load As Under:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) //This condition allows a code to execute once when your page is load first time.
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Some more text";
TextBox1.ForColor = System.Drawing.Color.Blue;
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}
try it, Simply try this code, this codes alway's work, don't need extra code
bool IsClick=false;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
if(IsClick)
{
TextBox1.Text = "Some more text";
TextBox1.ForeColor = System.Drawing.Color.Blue;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IsClick=true;
}
This is My Idea
Related
Got a problem with my project, I've one label and 3 checkboxes. What I want is if I unchecked one of checkboxes one label text is cleared. The problem of my code is if I uncheck one of the checkboxes, all labels text is cleared.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
if(checkBox1.Checked)
{
string lb1 = label1.Text + c.Text + "#";
lb1 = lb1.Replace("#", Environment.NewLine);
label1.Text = lb1;
}
else
{
label1.Text = "";
}
First of all you should assign checkBox1_CheckedChanged event handler to each CheckedChanged event of your checkboxes. If I understand your problem, the code should be as following:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
label1.Text = (label1.Tag as string);
if (checkBox1.Checked)
{
label1.Text += checkBox1.Text;
}
if (checkBox2.Checked)
{
label1.Text += checkBox2.Text;
}
if (checkBox3.Checked)
{
label1.Text += checkBox3.Text;
}
label1 += Environment.NewLine;
}
label1.Tag stores the initial value of your label1.Text. It should be assigned somewhere in Load event of your main window:
label1.Tag = label.Text;
How about this:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
if(checkBox1.Checked)
{
string lb1 = label1.Text + c.Text + "#";
lb1 = lb1.Replace("#", Environment.NewLine);
label1.Text = lb1;
}
else
{
string str = c.Text + "#";
str = str.Replace("#", Environment.NewLine);
label1.Text = label1.Text.Replace(str, "");
}
I have a Textbox with MultiLine enabled, in my application this Textbox controller used to insert some text.
All I want to do is to jump to a new line if the user clicks enter.
All I have tried is to find the write command inside my controller Enter event:
private void tbc_Enter(object sender, EventArgs e)
{
}
Is this what you want?
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "This" + Environment.NewLine + "A" + Environment.NewLine + "Multiline" + Environment.NewLine + "Textbox.";
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.AppendText(Environment.NewLine);
textBox1.Focus();
}
In the following I've taken out irrelevant code. I've created a field called printString. The calculateButton_Click method does a heap of stuff, then I want to send it to a print-friendly page using response.write. However the printString variable doesn't seem to ever stop being "DEFAULT". DEFAULT is all that shows up on my blank page when I click the printButton_Click. Trimmed code below:
public partial class _Default : System.Web.UI.Page
{
private string _printString = "DEFAULT";
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
}
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
}
When printButton is clicked it is using the value DEFAULT from when the variable is being set.
private string _printString = "DEFAULT";
Is your problem. You need to maintain the state of printString when the variable is modified. Simply assigning _printString to another value is not persisting the change. You could either write a function to assign _printString to the correct value when printButton is clicked, use ViewState or Session or assign _printString in the printButton click function directly as shown below.
protected void printButton_Click(object sender, EventArgs e)
{
_printString = "Harry Potter";
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
Will result in Harry Potter being wrote to the page.
To use Session:
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["PrintString"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
_printString = (string)Session["PrintString"];
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
ViewState:
ViewState["PrintString"] = "HarryPotter";
Then to retrieve the value you can simply do:
_printString = (string)ViewState["PrintString"];
http://msdn.microsoft.com/en-gb/library/ms972976.aspx
All (instance) variables are disposed at the end of the page's lifecycle since HTTP is stateless(even the controls). You could use a ViewState, HiddenField or Session variable instead.
private string PrintString
{
get
{
if (ViewState["PrintString "] == null || string.IsNullOrEmpty((String)ViewState["PrintString"]))
{
ViewState["PrintString"] = "DEFAULT";
}
return ViewState["PrintString"].ToString();
}
set { ViewState["PrintString"] = value; }
}
There are other options:
Nine Options for Managing Persistent User State in Your ASP.NET Application
The button click event is causing a postback and the _printString value is not being persisted. You need to store it in the calculate method via Session or Viewstate and then set it in the print for example: -
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["bigstring"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
_printString = Session["bigstring"].ToString();
Response.Write(_printString);
Response.Flush();
Response.End();
}
I have 3 checkboxes with corresponding message in a textbox. My teacher wants the message to remain in the textbox when the checkbox is still checked and hide the text when it is unchecked. In my case when I checked the 3 checkboxes their 3 corresponding messages will appear but when I unchecked one of the checkboxes and the other two are still checked, all the message will disappear. My problem is when I unchecked one of the checkbox and and the other 2 are still checked the corresponding messages with the remaining two checked checkboxes will remain in their textboxes.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
if (chkCarWheels.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
if (chkCarAcceleration.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
if (chkCarBreakpad.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
Looks like you need to create message depending on checkboxes states. You can create method, which will do the job and call it when state of some checkbox changed.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
Or the better one - create one event handler for all checkboxes:
// use for chkCarWheels, chkCarAcceleration, chkCarBreakpad
private void chkCar_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void BuildMessage()
{
lblMessage.Text = "My " + txtName.Text + " Car";
if (chkCarWheels.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
if (chkCarAcceleration.Checked)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
if (chkCarBreakpad.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
}
You don't need to compare boolean values with true/false. Use those values directly if (chkCarWheels.Checked). And keep in mind that in C# we use CamelCase names form methods. Also consider to use StringBuilder to build whole message and then assign it to label:
private void BuildMessage()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("My {0} Car", txtName.Text);
if (chkCarWheels.Checked)
sb.Append(mycar.hasWheels(4));
if (chkCarAcceleration.Checked)
sb.Append(mycar.Accelerate());
if (chkCarBreakpad.Checked)
sb.Append((mycar.hasBreak());
lblMessage.Text = sb.ToString();
}
Try this:
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
chkCar()
}
private void chkCar()
{
string msg="";
if (chkCarWheels.Checked)
msg=msg+mycar.hasWheels(4);
if(chkCarAcceleration.Checked)
msg=msg+mycar.Accelerate();
if(chkCarBreakpad.Checked)
msg=msg+mycar.hasBreak();
lblMessage.Text=msg;
}
I am dynamically creating buttons which each selection of a dropdownlist.
With the following code I am adding an event handler to each button.
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
private void button_Click(object sender, EventArgs e)
{
//Do something...
Response.Write("hello");
}
But unfortunately it does not fire that event and gives me an error as following
button_Click 'Index.button_Click(object, System.EventArgs)' is a 'method', which is not valid in the given context
How do I handle this?
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "Close", "javascript:OpenPopUp1();", true);
if (Session["filter"] == DropDownList1.SelectedValue)
{
}
else
{
if (Session["filter"] == "")
{
Session["filter"] = DropDownList1.SelectedValue + ":";
}
else
{
Session["filter"] = DropDownList1.SelectedValue + ":" + Session["filter"];
}
}
string asd = Session["filter"].ToString();
string[] split = asd.Split(':');
DropDownList1.Items.RemoveAt(DropDownList1.SelectedIndex);
for (int i = 0; i < split.Count(); i++)
{
string filter = split[i].ToString();
Button button = new Button();
button.Text = split[i].ToString();
button.ID = split[i].ToString();
button.Attributes.Add("onclick", "remove(" + split[i].ToString() + ")");
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
}
}
The above shows the whole code of dropdownselected index.
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
} // <-- end your current method with a curly brace
// Now start a new method
private void button_Click(object sender, EventArgs e)
{
//do something...
Response.Write("hello");
}
It's hard to say what you're going after, as there are a number of issues going on here. Since your dynamically generated buttons are being created in the SelectedIndexChanged event handler of your dropdown, they are not going to exist, nor are their event bindings, on the next postback. This means they can show up on the page, but clicking them won't do anything.
Secondly, since you are storing the SelectedValue to Session, and then using that value to set the Button IDs, you are going to be creating buttons with duplicate IDs if the user ever comes back to the page. (I noticed you are removing the list item once selected, but it would come back if the user refreshed the page, while the session object would remain populated.)
Last oddity, I wasn't able to find where your particular exception is handling, nor able to reproduce it. Which version of .NET are you programming against? Are you invoking the button click event anywhere from code-behind?
Now, that all said, I'm providing the following fix (or at least improvement):
protected void Page_Init(object sender, EventArgs e)
{
CreateButtons();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "Close", "javascript:OpenPopUp1();", true);
if (Session["filter"] == DropDownList1.SelectedValue)
{
}
else
{
if (Session["filter"] == "")
{
Session["filter"] = DropDownList1.SelectedValue + ":";
}
else
{
Session["filter"] = DropDownList1.SelectedValue + ":" + Session["filter"];
}
}
DropDownList1.Items.RemoveAt(DropDownList1.SelectedIndex);
CreateButtons();
}
private void CreateButtons()
{
PlaceHolder1.Controls.Clear();
if (Session["filter"] != null)
{
string asd = Session["filter"].ToString();
string[] split = asd.Split(':');
for (int i = 0; i < split.Count(); i++)
{
string filter = split[i].ToString();
Button button = new Button();
button.Text = split[i].ToString();
button.ID = split[i].ToString();
button.Attributes.Add("onclick", "remove(" + split[i].ToString() + ")");
button.Click += new System.EventHandler(button_Click);
PlaceHolder1.Controls.Add(button);
}
}
}
private void button_Click(object sender, EventArgs e)
{
//do something...
Response.Write("hello");
}