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;
}
Related
I have a "listview" for showing list of employee and a "dropdownlist" to select department. The following error occurs when I use "DropDownlist" for 3rd or second time:
"Failed to load viewstate".
The control tree into which viewstate is being loaded must match the control tree that was used to save "viewstate" during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request."
This is asp.net Webform and I have to use this technology and have no other choice .
namespace .Presentation.general
{
public partial class Listg : PageBase
{
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/App_MasterPages/empty.Master";
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDepartmentsDropDownList();
GeneralObjectDataSource.SelectParameters["Department"].DefaultValue = "";
decimal presence = Convert.ToDecimal(Data.EmployeeDB.Create().GetCountEMPOnlineToday());
decimal visibles = Convert.ToDecimal(Data.EmployeeDB.Create().GetCountVisiblesEmployees());
visibles = (visibles == 0 ? 1 : visibles);
PresenceLabel.Text = System.Math.Round((presence / visibles) * 100, 1).ToString() + "% " + string.Format(" ({0})", presence);
}
}
public void Search(object sender, EventArgs e)
{
GeneralObjectDataSource.SelectParameters["name"].DefaultValue = Common.Converter.ConvertToFarsiYK(NameTextBox.Text.Trim());
if (PresenceRadioBottonList.SelectedValue == "1")
{
GeneralObjectDataSource.SelectParameters["onlyPresence"].DefaultValue = "true";
}
else
{
GeneralObjectDataSource.SelectParameters["onlyPresence"].DefaultValue = "false";
}
DataListView.DataBind();
}
public void select_department_SelectedIndexChanged(object sender, EventArgs e)
{
GeneralObjectDataSource.SelectParameters["name"].DefaultValue = "";
GeneralObjectDataSource.SelectParameters["Department"].DefaultValue = select_department.SelectedItem.Text;
GeneralObjectDataSource.DataBind();
DataListView.DataBind();
}
private void PopulateDepartmentsDropDownList()
{
select_department.DataSource = Biz.EmployeeBO.GetDepartments();
select_department.DataTextField = "Name";
select_department.DataValueField = "ID";
select_department.DataBind();
select_department.Items.Insert(0, new ListItem("", "0"));
select_department.SelectedValue = Biz.Settings.SelectedDepartmentID;
}
}
}
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();
}
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
I have a quick and simple question on a small project that I'm starting out on my own in C# for a Windows form program with Visual Studio 2010. I can't seem to find the correct code to transfer the input data that a user enters into a textbox with a method where they hit the enter key and it automatically enters a message in that label on the same form.
Such as in the following code (which has been edited as suggestions are provided):
namespace MovieFinders2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
//Named "Enter a Year"
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
label2.Text = textBox1.Text;
label2.Text = "Movies released before " + textBox1.Text;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
label2.Text = textBox1.Text;
label2.Text = "Movies released before " + textBox1.Text;
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
label3.Text = textBox1.Text;
label3.Text = "Movies released in or after " + textBox1.Text;
}
}
}
private void label3_Click(object sender, EventArgs e)
{
label3.Text = textBox1.Text;
label3.Text = "Movies released in or after " + textBox1.Text;
}
}
}
I know that this program is in the early stages, but I"m trying to take this one step at a time and this is the road block that I have encoutered at this point; so any and all help would be greatly appreciated. Right now when I click the mouse on the lable it displays the message in that label. I need this to appear in the label when the user presses the enter key.
Try this:
void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {
label2.Text = textBox1.Text;
label2.Text = "Movies released before " + textBox1.Text;
}
}
TextBox.KeyDown event
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");
}