Access dynamically created checkbox values in c# - c#

I have added a CheckBox dynamically in asp.net
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
I can access this CheckBox via c# in pageLoad itself, just after declaring above codes.
But when I try to access this values after a button click I'm getting null values.
CheckBox cb1 = (CheckBox)ph.FindControl("1");
Response.Write(cb1.Text);
ph.Controls.Add(cb);
(ph is a placeholder)
Can any one tell me whats wrong here?

You need to recreate the checkbox everytime the page posts back, in Page_Load event, as it's dynamically added to page.
Then you can access the checkbox later in button click event.
// Hi here is updated sample code...
Source
<body>
<form id="frmDynamicControl" runat="server">
<div>
<asp:Button ID="btnGetCheckBoxValue" Text="Get Checkbox Value" runat="server"
onclick="btnGetCheckBoxValue_Click" />
</div>
</form>
</body>
code behind
protected void Page_Load(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
frmDynamicControl.Controls.Add(cb);
}
protected void btnGetCheckBoxValue_Click(object sender, EventArgs e)
{
CheckBox cb1 = (CheckBox)Page.FindControl("1");
// Use checkbox here...
Response.Write(cb1.Text + ": " + cb1.Checked.ToString());
}

After you click the button it will post back the page which will refresh the state. If you want the values to be persistent then you'll need to have them backed inside the ViewState or similar.
private bool CheckBox1Checked
{
get { return (ViewState["CheckBox1Checked"] as bool) ?? false; }
set { ViewState["CheckBox1Checked"] = value; }
}
void Page_load(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
cb.Checked = CheckBox1Checked;
cb.OnCheckedChanged += CheckBox1OnChecked;
// Add cb to control etc..
}
void CheckBox1OnChecked(object sender, EventArgs e)
{
var cb = (CheckBox)sender;
CheckBox1Checked = cb.Checked;
}

I'm a bit later here, but i just do:
try{
if(Request.Form[checkboxId].ToString()=="on")
{
//do whatever
}
}catch{}
If a checkbox is not checked, it will not appear in the Form request hence the try catch block. Its quick, simple, reusable, robust and most important, it just works!

Related

CheckBox CheckedChanged event added from code behind

I have a couple of checkboxes that I add from my code behind, but I can't get the CheckedChanged event to fire.
This code is being called on page load:
CheckBox cb = new CheckBox();
cb.AutoPostBack = true;
cb.CheckedChanged += cb_CheckedChanged;
cb.ToolTip = dr["Id"].ToString();
cb.ID = Guid.NewGuid().ToString();
Label lbl = new Label();
lbl.Text = dr["Id"].ToString();
lbl.AssociatedControlID = cb.ID;
dvCheckboxes.Controls.Add(cb);
dvCheckboxes.Controls.Add(lbl);
dvCheckboxes.Controls.Add(new LiteralControl("<br />"));
And the event:
void cb_CheckedChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write(((CheckBox)sender).ToolTip);
}
I've put a breakpoint in the CheckedChanged event, but it's never reached.
What I've tried:
putting the code in if(!IsPostBack), but no difference.
cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
cb.CheckedChanged += new EventHandler(this.cb_CheckedChanged);
cb.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
tried putting the code in Page_Init instead of Page_Load
#johan, Try this. Create the checkboxes in PageInit instead of Pageload. Also provide an appropriate id for the Checkbox.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_init(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.AutoPostBack = true;
cb.CheckedChanged +=cb_CheckedChanged;
cb.CausesValidation = false;
cb.ToolTip = "Hello";
cb.ID = "chk_test";
Label lbl = new Label();
lbl.Text = "test";
lbl.AssociatedControlID = cb.ID;
dvCheckboxes.Controls.Add(cb);
dvCheckboxes.Controls.Add(lbl);
dvCheckboxes.Controls.Add(new LiteralControl("<br />"));
}
protected void cb_CheckedChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write(((CheckBox)sender).ToolTip);
}
Add event in your site code - not code behind:
<asp:CheckBox ID="cb" Runat="server" CheckedChanged="cb_CheckedChanged" />
Hope this helps.

How to handle events of dynamically added checkbox on windows form

I am able to add checkbox dynamically on windows form and add data value to its text property. On click of any checkbox I have run a procedure which will make certain other checkbox disabled.
I am not able to find eventhandler for it.
Have you tried this
CheckBox check = new CheckBox();
check.Checked = true;
check.AccessibleName = checkName;
check.Location = new System.Drawing.Point(340, 40);
check.CheckedChanged +=new EventHandler(check_CheckedChanged);
this.Controls.Add(check);
private void custom_event_handler(object sender, EventArgs e)
{
....
}
and then you add checbox like this:
CheckBox cb = new CheckBox();
cb.CheckedChanged += new EventHandler(custom_event_hahndler);
if the name of the dynamically added checkbox is c, the answer is as below:
c.CheckedChanged += c_CheckedChanged;
and c_CheckedChanged is as below:
private void c_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
((CheckBox)(this.Controls.Find("c1", false))[0]).Enabled = false;
}
}
which c1 is the name of the checkbox you want to disable.
Add event handler when you create a checkbox programmatically. And its handler you can do your code logic.
CheckBox dynamicCheckBox = new CheckBox();
dynamicCheckBox.CheckedChanged +=new EventHandler(dynamicCheckBox_CheckedChanged);
private void dynamicCheckBox_CheckedChanged(object sender, EventArgs e)
{
// Your code
}

Checkbox added programmatically not found

I add checkboxes that way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
}
}
but when I try to get this checkboxes from form:
foreach (Control item in FindControl("FieldForm").Controls)
{
if (item is Panel)
{
foreach (Control checkbox in item.Controls)
i cannot find this checkboxes :/ This could be problem with runat=server? I not find this property in Checkbox ..
If you want to find this CheckBox after PostBack (what I've assumed), you need to recreate it. Try to create this CheckBox out of if(!PostBack) clause (so it's recreated after postback too):
protected void Page_Load(object sender, EventArgs e)
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
if (!IsPostBack)
{
// ....
}
}
You must have to use Page_Load even to add controls dynamically.
protected void page_load()
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
}
you may simply use a better method of finding your control
just use this
CheckBox chkBox = this.form1.FindControl("YourControlId") as CheckBox;

Sorting Gridview breaks ModalPopUp in GridView

I have a gridview that has linkbuttons that call modalpopups and textboxes with values. I am trying to implement sorting for the gridview, but the if(!ispostback) statement I need for sorting prevents the modalpopup from appearing. It also does not sort the textboxes in the gridview. Is there a way to implement sorting without using ispostback in the page_load?
Here is the code for the modalpopup, gridview binding and sorting.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["sortOrder"] = "";
Bind_Gridview("", "");
loadModals();
}
}
protected void viewModal(object sender, EventArgs e)
{
...
mainPanel.Controls.Add(exstModal);
mainPanel.Controls.Add(exstModalBox);
exstModalBox.Show();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
Bind_Gridview(e.SortExpression, sortOrder);
}
public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
protected void gv1_RowCommand(object sender, GridViewRowEventArgs e)
{
...
CheckBox cb = new CheckBox();
TextBox ca = new TextBox();
ca.Width = 20;
TextBox cga = new TextBox();
cga.Width = 20;
if (e.Row.RowType == DataControlRowType.DataRow) //Foreach row in gridview
{
while (dr1.Read())
{
ca.Text = dr1["cyla"].ToString();
cga.Text = dr1["cga"].ToString();
checkText = dr1["completed"].ToString();
if (checkText == "True")
{
cb.Checked = true;
}
else
{
cb.Checked = false;
}
}
...
dr1.Close();
conn1.Close();
e.Row.Cells[6].Controls.Add(ca);
e.Row.Cells[8].Controls.Add(cga);
e.Row.Cells[9].Controls.Add(cb);
...
}
A GridView has built-in sorting capabilities. Depending on the dataset you are using to populate the data, you likely don't need to manually handle anything manually, let alone with the ViewState.
Check out the second example on this MSDN page and note that it never does anything manually with the ViewState... the OnSorting and OnSorted events are there just to display extra information or to impose requirements:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
If you post a bit more of your code (including your .aspx pages, the markup for the modal popups, and the code for the loadModals() function, we might be able to better help you.

Dynamically Creating Multiple controls which use a common handler

This first section is in a loop. It creates the dynamic check boxes with no problems.
// All I am doing here is incrementing our session counter
int id = Convert.ToInt32(Session["id"]);
id++;
Session["id"] = id;
// Now I create my checkbox
chkDynamic = new CheckBox();
chkDynamic.Text = "hey";
string chk = "chk" + id.ToString();
chkDynamic.ID = chk;
chkDynamic.CheckedChanged += new EventHandler(this.chkDynamic_CheckedChanged);
Panel1.Controls.Add(chkDynamic);
My event handler is not wiring up for this. Strangly if I hard code the ID it does work, but only for one iteration of the loop because if we hard coded the IDs then we would run into 'multiple id errors'
protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
if (chkDynamic.Checked)
Response.Write( "you checked the checkbox");
else if (!chkDynamic.Checked)
Response.Write("checkbox is not checked");
}
You need to check sender in your event handler to know which checkbox sent the event:
protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
Response.Write( "you checked the checkbox");
else
Response.Write("checkbox is not checked");
}

Categories

Resources