[c#] How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

I am creating a CheckBoxList in a class file and am using an HTMLTextWriter to render the control.

I'm using the following code to store the selected values in a string:

string YrStr = "";
for (int i = 0; i < YrChkBox.Items.Count; i++)
{
    if (YrChkBox.Items[i].Selected)
    {
        YrStr += YrChkBox.Items[i].Value + ";"; 
    }
}

I stepped through the code and it doesn't seem to hit the inside of the if statement & the selected value attribute is false every time ... Anyone have an idea of how I can address this?

I populate it using the following:

 YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));

This question is related to c# asp.net html htmltextwriter

The answer is


// Page.aspx //

// To count checklist item

  int a = ChkMonth.Items.Count;
        int count = 0;

        for (var i = 0; i < a; i++)
        {
            if (ChkMonth.Items[i].Selected == true)
            {
                count++;
            }
        }

// Page.aspx.cs //

  // To access checkbox list item's value //
   string YrStrList = "";
        foreach (ListItem listItem in ChkMonth.Items)
        {
            if (listItem.Selected)
            {
                YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
            }

        }

        sMonthStr = YrStrList.ToString();

// aspx.cs

// Load CheckBoxList selected items into ListBox

    int status = 1;
    foreach (ListItem  s in chklstStates.Items  )
    {
        if (s.Selected == true)
        {
            if (ListBox1.Items.Count == 0)
            {
                ListBox1.Items.Add(s.Text);

            }
            else
            {
                foreach (ListItem list in ListBox1.Items)
                {
                    if (list.Text == s.Text)
                    {
                        status = status * 0;

                    }
                    else
                    {
                        status = status * 1;
                    }
                }
                if (status == 0)
                { }
               else
                {
                    ListBox1.Items.Add(s.Text);
                }
                status = 1;
            }
        }
    }
}

An elegant way to implement this would be to make an extension method, like this:

public static class Extensions
{
    public static List<string> GetSelectedItems(this CheckBoxList cbl)
    {
        var result = new List<string>();

        foreach (ListItem item in cbl.Items)
            if (item.Selected)
                result.Add(item.Value);

        return result;
    }
}

I can then use something like this to compose a string will all values separated by ';':

string.Join(";", cbl.GetSelectedItems());

check boxlist selected values with seperator

 string items = string.Empty;
        foreach (ListItem i in CheckBoxList1.Items)
        {
            if (i.Selected == true)
            {
                items += i.Text + ",";
            }
        }
        Response.Write("selected items"+ items);

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to htmltextwriter

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart