9

I'm programmatically adding checkboxes to a ASP.NET WebForm. I want to iterate through the Request.Form.Keys and get the value of the checkboxes. ASP.NET Checkboxes don't have a value attribute.

How do I set the value attribute so that when I iterate through the Request.Form.Keys I get a more meaningful value than the default "on".

Code for adding the checkboxes to the page:

List<string> userApps = GetUserApplications(Context);

Panel pnl = new Panel();

int index = 0;
foreach (BTApplication application in Userapps)
{
    Panel newPanel = new Panel();
    CheckBox newCheckBox = new CheckBox();

    newPanel.CssClass = "filterCheckbox";
    newCheckBox.ID = "appSetting" + index.ToString();
    newCheckBox.Text = application.Name;

    if (userApps.Contains(application.Name))
    {
        newCheckBox.Checked = true;
    }

    newPanel.Controls.Add(newCheckBox);
    pnl.Controls.Add(newPanel);

    index++;
}

Panel appPanel = FindControlRecursive(this.FormViewAddRecordPanel, "applicationSettingsPanel") as Panel;

appPanel.Controls.Add(pnl);

Code for retrieving checkbox values from Request.Form:

StringBuilder settingsValue = new StringBuilder();

foreach (string key in Request.Form.Keys)
{
    if (key.Contains("appSetting"))
    {
        settingsValue.Append(",");
        settingsValue.Append(Request.Form[key]);
    }
}

1 Answer 1

18

CheckBox.InputAttributes.Add()! - learn.microsoft.com

The following doesn't work because:

the CheckBox control does not render the value attributed (it actually removes the attribute during the render event phase).

newCheckBox.Attributes.Add("Value", application.Name);

The solution:

newCheckBox.InputAttributes.Add("Value", application.Name);

Thanks to Dave Parslow's blog post: Assigning a value to an ASP.Net CheckBox

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.