简体   繁体   中英

set multiple selected value on select2 multiple in asp.net dropdownlist from C#

I need to add multiple author under a book. So i have used "Select2 Multiple" in asp dropdownlist. I was able to insert data but in edit mode i can't assign multiple selected value on dropdownlist.

在此处输入图片说明

My dropdownlist in aspx page is

    <asp:DropDownList ID="ddlAuthor" runat="server" multiple="multiple" data-placeholder="Select Author (s)" CssClass="form-control select2"></asp:DropDownList>

In C# i have tried as following but it add only one value. My c# code is

        foreach (DataRow row in dtAuthor.Rows)
        {
           ddlAuthor.Items.FindByValue(row["AUTHOR_ID"].ToString()).Selected = true;
        }

Any suggestion about how can i set multiple selected value in edit mode from c#?

You can't use a DropDownList to achieve this, use a listBox like this :

    <asp:ListBox ID="ddlAuthor" runat="server" SelectionMode="Multiple" data-placeholder="Select Author (s)" CssClass="form-control select2"></asp:ListBox>

And your code behind will work.

EDIT :

Here is a example of code behind for you :

        //I bind my ListBox with random data 
        List<string> data = new List<string>() { "Flo", "Auteur", "Patrick","Test" };
        //Databind
        ddlAuthor.DataSource = data;
        ddlAuthor.DataBind();

        //Here is my selected values, i wish that this values are selected
        List<string> selected = new List<string>() { "Flo", "Patrick" };

        //Foreach value in my selected list i select the proper value in my listbox
        foreach (string row in selected)
        {
            ddlAuthor.Items.FindByValue(row).Selected = true;
        }

you aren't using select2 in this case ! you need to use select2, and push all you multiple data into a variable and send it to js function or use ajax

$(".ddlAuthor").select2('data', youDataHere);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM