简体   繁体   中英

How to retrieve binded listbox in multiple selection mode from code behind in ASP.NET in C#?

I have chosen listbox . I have no problem to add items to the database from this listbox, but when I want to edit my post and retrieve these Tags from the database to this listbox, I cant add selected items from the database.

I need to retrieve and add selected Tags by user to this list box since the user needs to look at his selected Tags.

My code is below:

<asp:SqlDataSource ID="sqldsSkillsNeed" runat="server" ConnectionString='<%$ ConnectionStrings:NetProjectsConnStr %>' SelectCommand="SELECT * FROM [tblAutoTags]"></asp:SqlDataSource>
<asp:ListBox ID="lstSkills" data-placeholder="your skills" SelectionMode="Multiple" CssClass="form-control chosen-select chosen-rtl" TabIndex="8" runat="server" DataSourceID="sqldsSkillsNeed" DataTextField="TagTitle" DataValueField="id"></asp:ListBox>

and code behind like this

string str = dt.Rows[0]["skills"].ToString();
string[] values = str.Split(',');

foreach (string value in values)
{
    if (value.Trim() == "")
       continue;
    lstSkills.Items.Add(value);
}

This code works correctly, but did not retrieve the selected Tags in list box in this line:

lstSkills.Items.Add(value);

Just try using FindByValue property of Listview as follow...

    foreach (string str in selectedStr)
    {
        if(lstSkills.Items.FindByValue(str) != null) 
        { 
              lstSkills.Items.FindByValue(str).Selected = true; 
        } 
    }

try this

    string[] values = str.Split(',');

    lstSkills.Items.AddRange(values);

ty my problem resolved, but now i need to delete selected item from listbox but still keep selected item? look this picture: ListBox Image in this image you can see selected items but these items is double and i need to delete selected items from list

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