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

被刻印的时光 ゝ 提交于 2019-12-12 05:42:39

问题


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#?


回答1:


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;
        }



回答2:


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);


来源:https://stackoverflow.com/questions/38069081/set-multiple-selected-value-on-select2-multiple-in-asp-net-dropdownlist-from-c-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!