None
None

Reputation: 5670

Access dynamically created checkbox values in 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?

Upvotes: 6

Views: 12165

Answers (3)

Sabs
Sabs

Reputation: 15

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!

Upvotes: 0

Amol
Amol

Reputation: 119

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());
}

Upvotes: 2

Dustin Kingen
Dustin Kingen

Reputation: 21265

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;
}

Upvotes: 1

Related Questions