Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value attribute to ASP.NET Checkbox

Tags:

c#

asp.net

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]);
    }
}
like image 839
M. Travis Volker Avatar asked Dec 05 '12 21:12

M. Travis Volker


1 Answers

InputAttributes.Add()!

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

like image 51
M. Travis Volker Avatar answered Sep 21 '22 17:09

M. Travis Volker