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, "");
}
Related
I'm reading a list of id numbers from a database table into a placeholder textbox but however; if I do a button click the data is removed.
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
i++;
}
}
This is a common problem when working with dynamically added controls in web forms (especially if you're coming from a winforms background). Pages in ASP.NET Web Forms are stateless, and reconstructed on each postback. Therefore, if you add a control to a page during a server event, you'll also have to add it to the page on subsequent Page loads if you want it to appear. You can accomplish this with something similar to the following:
protected List<Control> ControlCache
{
get => (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>());
set => Session["cachedControlsForPageX"] = value;
}
/* If you can't use C# 7's expression bodied property accessors, here's the equivalent in blocks:
protected List<Control> ControlCache
{
get { return (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>()); }
set { Session["cachedControlsForPageX"] = value; }
}
*/
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
foreach (var control in ControlCache)
{
ContentPlaceHolder1.Controls.Add(control);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
}
}
else
ControlCache = null;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
ControlCache.Add(txt);
i++;
}
}
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
Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.
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");
}