从数据表中选择多个值到列表框

从数据表中选择多个值到列表框

问题描述:

我从数据库到数据表中获取记录,这些记录在每行班加罗尔,德里,孟买"中都包含名称城市"和值"列.
我现在有了一个列表框控件,如何在浏览器上自动在列表框中选择三个城市.请帮助我

I take records from database to datatable that contain a column Name city and value as like this in each row "Bangalore,DelMumbai".
I have a listbox control now how i select three city in listbox automatically on browser.Please help me

尝试以下方法

样本列表框
Try the below approach

Sample listbox
<asp:ListBox ID="Listbox1" runat="server" SelectionMode="Multiple">
   <asp:ListItem Text="Bangalore" Value="Bangalore"></asp:ListItem>
   <asp:ListItem Text="Delhi" Value="Delhi"></asp:ListItem>
   <asp:ListItem Text="Chennai" Value="Chennai"></asp:ListItem>
   <asp:ListItem Text="Mumbai" Value="Mumbai"></asp:ListItem>
   </asp:ListBox>



在后面的代码中



in code behind

string Cities = "Bangalore,Delhi,Mumbai";
string[] strCity = Cities.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

foreach (string city in strCity)
{
    if (Listbox1.Items.FindByText(city) != null)
    {
        Listbox1.Items.FindByText(city).Selected = true;
    }
}


您需要在load事件中编写此类代码.
You need to write this type of code in your load event.
string qry = "SELECT CityName,(case when CityName in('Bangalore','Delhi','Mumbai')  then 1 else 0 end  ) as Selected FROM CityTable";
           System.Data.DataTable dtbcity = Get_data(qry).Tables[0];
           lstCity.DataSource = dtbcity;
           lstCity.DisplayMember = "CityName";
           lstCity.ValueMember = "CityName";
           lstCity.SelectionMode = SelectionMode.MultiSimple;
           foreach (DataRow item in dtbcity.Rows)
           {
               if (item["Selected"].ToString() == "1")
                   lstCity.SelectedValue = item["CityName"];
           }