Adding SelectedIndexChanged to generated checkboxlist

I have a generated checkboxlist that is generated by selecting options in another checkbox:

CheckBoxList typefilter = new CheckBoxList { ID = "typefilter" + CheckBoxList1.Items[i].Text };
typefilter.RepeatDirection = RepeatDirection.Horizontal;
SortedList<int, string> filterValueList = new SortedList<int, string>();

typefilter.DataTextField = "Value";
typefilter.DataValueField = "Key";
typefilter.DataSource = getFilterOptions(int.Parse(CheckBoxList1.Items[i].Value));
typefilter.DataBind();

phSelectedItem.Controls.Add(typefilter);

      

Now the problem is if I want to give the generated checkboxlist the SelectedIndexChanged value, how should I do this?

Edit (after using the suggested handler method, clicking the checkmark will destroy the entire checkboxlist): All method code

protected void cbl_RentalCategory_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cbl_RentalCategory.Items.Count > 0)
    {
        Label selectedType = new Label { ID = "Title" };
        selectedType.Text = "<h3>Rental Items</h3>";

        phSelectedItem.Controls.Add(selectedType);
    }

    for (int i = 0; i < cbl_RentalCategory.Items.Count; i++)
    {
        if (cbl_RentalCategory.Items[i].Selected)
        {
            Label selectedType = new Label { ID = "selectedType" + cbl_RentalCategory.Items[i].Text };
            selectedType.Text = cbl_RentalCategory.Items[i].Text + "<br/>";

            phSelectedItem.Controls.Add(selectedType);

            CheckBoxList typefilter = new CheckBoxList { ID = "typefilter" + cbl_RentalCategory.Items[i].Text };
            typefilter.RepeatDirection = RepeatDirection.Horizontal;
            SortedList<int, string> filterValueList = new SortedList<int, string>();
            typefilter.AutoPostBack = true;
            typefilter.SelectedIndexChanged += typefilter_SelectedIndexChanged;
            typefilter.DataTextField = "Value";
            typefilter.DataValueField = "Key";
            typefilter.DataSource = getFilterOptions(int.Parse(cbl_RentalCategory.Items[i].Value));
            typefilter.DataBind();

            phSelectedItem.Controls.Add(typefilter);

            Label nextLine = new Label { ID = "nextLine" + cbl_RentalCategory.Items[i].Text };
            nextLine.Text = "<br/>";
            phSelectedItem.Controls.Add(nextLine);
        }
    }
}

      

getFilterOptions ():

private SortedList<int, string> getFilterOptions(int typeID)
{
    SortedList<int, string> filterValueList = new SortedList<int, string>();

    string strConnectionString = ConfigurationManager.ConnectionStrings["SOMEDB"].ConnectionString;
    SqlConnection conn = new SqlConnection(strConnectionString);

    using (SqlCommand cmd = new SqlCommand("Select * FROM SOMEWHERE WHERE ID=@ID", conn))
    {
        conn.Open();
        cmd.Parameters.AddWithValue("@ID", typeID);
        cmd.ExecuteNonQuery();
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            filterValueList.Add(int.Parse(reader["ID"].ToString()), reader["InformationHeader"].ToString());
        }

        conn.Close();
    }

    return filterValueList;
}

      

+3


source to share


3 answers


If I understand your problem correctly, you need to dynamically create a checkboxlist, and this dynamically created checkboxlist should also support AutoPostBack with the SelectedChange event.

Steps to run the sample:

Step 1: Create a Simple Website in Visual Studio

Step-2: Place below code in default.aspx.cs file, leave using namespace as they are.

Step-3: place the aspx code in the default.aspx file

Expected Result: A list of checkboxes will appear when the page loads by default. Select any item from the dropdown list. The code will generate a separate checkboxlist (subitem) for each selection. Select any item in the separate checkbox list and the selected value will be displayed on the Shortcut screen.



public partial class _Default : System.Web.UI.Page
{
string[] arrMasterDDLSelItem;
protected void Page_Load(object sender, EventArgs e)
{
    if (masterCheckBoxList.SelectedItem != null)
    {
        arrMasterDDLSelItem = new string[masterCheckBoxList.Items.Count];
        ListItem objListItem;
        for (int index = 0; index < masterCheckBoxList.Items.Count; index++)
        {
            objListItem = masterCheckBoxList.Items[index] as ListItem;
            if (objListItem.Selected)
                arrMasterDDLSelItem[index] = objListItem.Text;
        }
        if (arrMasterDDLSelItem.Count() > 0)
            RecreateControls(arrMasterDDLSelItem);
    }
}
protected void typefilter_SelectedIndexChanged(object sender, EventArgs e)
{
    CheckBoxList objCheckBoxList = sender as CheckBoxList;
    ListItem objListItem;
    string selectedItems=string.Empty;
    foreach (var item in objCheckBoxList.Items)
    {
        objListItem=item as ListItem;
        if (objListItem.Selected)
            selectedItems += " " + objListItem.Text + ",";
    }
    Label1.Text = selectedItems;
}

private SortedList<int, string> getFilterOptions(string selItem)
{
    SortedList<int, string> filterValueList = new SortedList<int, string>();
    for (int index = 0; index < 10; index++)
        filterValueList.Add(index, "SubItem -" + index.ToString() + " For " + selItem);
    return filterValueList;
}
private void RecreateControls(string[] masterSelectedItem)
{
    foreach (var item in masterSelectedItem)
    {
        if (item != null)
        {
            CheckBoxList typefilter = new CheckBoxList { ID = "typefilter" + item };
            typefilter.RepeatDirection = RepeatDirection.Horizontal;
            SortedList<int, string> filterValueList = new SortedList<int, string>();
            typefilter.AutoPostBack = true;
            typefilter.SelectedIndexChanged += new System.EventHandler(typefilter_SelectedIndexChanged);
            typefilter.DataTextField = "Value";
            typefilter.DataValueField = "Key";
            typefilter.DataSource = getFilterOptions(item);
            typefilter.DataBind();
            ContentPlaceHolder MainContent = (ContentPlaceHolder)this.Master.FindControl("MainContent");
            MainContent.Controls.Add(typefilter);
        }
    }
}

      

}

ASPX code:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content><asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:CheckBoxList ID="masterCheckBoxList" runat="server" AutoPostBack="true">
        <asp:ListItem Text="Type-1" Value="1"></asp:ListItem>
        <asp:ListItem Text="Type-2" Value="2"></asp:ListItem>
        <asp:ListItem Text="Type-3" Value="3"></asp:ListItem>
    </asp:CheckBoxList>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <asp:Panel ID="pnlDropDownList" runat="server">
    </asp:Panel>
</asp:Content>

      

The apology code may have an optimization scope written in a very limited period of time to only give an idea of ​​how to solve your problem. But tested and works great with the above details. Note. The link for this example is taken from http://www.aspsnippets.com/Articles/Creating-Dynamic-DropDownList-Controls-in-ASP.Net.aspx

0


source


Here's how you can do it. Set Autopostback

to true and create a method selectedindexchanged

. Make sure this code only runs the first time the page is loaded.

if(!IsPostBack){
CheckBoxList typefilter = new CheckBoxList { ID = "typefilter" + CheckBoxList1.Items[i].Text };
typefilter.RepeatDirection = RepeatDirection.Horizontal;
SortedList<int, string> filterValueList = new SortedList<int, string>();
typefilter.AutoPostBack = true;
typefilter.SelectedIndexChanged += typefilter_SelectedIndexChanged;
typefilter.DataTextField = "Value";
typefilter.DataValueField = "Key";     
typefilter.DataSource = getFilterOptions(int.Parse(CheckBoxList1.Items[i].Value));
typefilter.DataBind();

phSelectedItem.Controls.Add(typefilter);
}

      



and here you have selected the method to change indexex

public void typefilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        //your code
    }

      

+1


source


Is there any specific reason why you are creating CheckBoxList from code?

As I understand it, your requirement is to show the main checkbox (RentalCategory) and for each selection of that checkbox show the label (selectedType *) and another list of checkboxes (typefilter *).

For such a requirement, I would use a relay that has a selected tick mark and a CheckBoxList typefilter selected in the item template, assigning a SelectedIndexChanged event handler to the typefilter only at design time.

From the code, I will execute 2 select statements (one in the main table-RentalCategory, the other in the detailed typefilter with the appropriate filter condition: where @ID in (<ID of the selected checkboxes in the RentalCategory list>);) at one time [guess: you have too much data]

This will give me a DataSet with 2 DataTables. I'll add 1 DataRelation and use this complete DataSet to bind with the main checkbox as well as the relay (with Row.GetChildRows or CreateChildView).

For understanding the proof of concept: http://support.microsoft.com/kb/306154 http://www.aspnettutorials.com/tutorials/controls/nestedrepeaters-csharp/

0


source







All Articles