Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access dynamically created checkbox values in c#

Tags:

c#

asp.net

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?

like image 492
None Avatar asked Jul 31 '13 11:07

None


2 Answers

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());
}
like image 140
Amol Avatar answered Nov 06 '22 11:11

Amol


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;
}
like image 1
Dustin Kingen Avatar answered Nov 06 '22 11:11

Dustin Kingen