如何从c#中的列表框中获取多个选定值?

时间:2023-01-18 18:08:43

I am doıng a email sender as a part of my program. In the form , I have listbox that is loaded with this code:

我是电子邮件发件人,作为我程序的一部分。在表单中,我有列表框加载此代码:

connection = new SqlConnection(connectionString);
        connection.Open();
        string sql = "SELECT Email,(CONVERT(varchar(2),FlatNo)+'- '+Name+' '+Surname) AS FullName FROM People " +
                     "ORDER BY FlatNo ";

        SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        listBox1.DisplayMember="FullName";
        listBox1.ValueMember = "Email";
        listBox1.DataSource = dt;
        connection.Close();

I have sendEmail(string toPerson) function. When I click the send button, I call email function as sendEmail(listbox1.selectedValue). It works if I choose one item but when I select multpile items , it only sends 1th one. How can I loop into selectedValues?

我有sendEmail(string toPerson)函数。当我单击发送按钮时,我将电子邮件功能称为sendEmail(listbox1.selectedValue)。如果我选择一个项目但是当我选择多个项目时,它只会发送第1个项目。我怎样才能循环到selectedValues?

2 个解决方案

#1


0  

Use the SelectedItems property the get multiple selection values: https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems(v=vs.110).aspx

使用SelectedItems属性获取多个选择值:https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems(v = vs.110).aspx

Or you can used the SelectedIndices property the get the index of the selected items instead.

或者您可以使用SelectedIndices属性来获取所选项的索引。

#2


0  

foreach (var listBoxItem in listBox1.Items )
         {
           list<string> x=new list<string>();
           if(listBox1.SelectedItem==true)
           {
            x.add(listBox1.SelectedItem[i];
           } 

        } 

now you have the List x which contains all selected items from listbox

现在您有List x,其中包含列表框中的所有选定项目

#1


0  

Use the SelectedItems property the get multiple selection values: https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems(v=vs.110).aspx

使用SelectedItems属性获取多个选择值:https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems(v = vs.110).aspx

Or you can used the SelectedIndices property the get the index of the selected items instead.

或者您可以使用SelectedIndices属性来获取所选项的索引。

#2


0  

foreach (var listBoxItem in listBox1.Items )
         {
           list<string> x=new list<string>();
           if(listBox1.SelectedItem==true)
           {
            x.add(listBox1.SelectedItem[i];
           } 

        } 

now you have the List x which contains all selected items from listbox

现在您有List x,其中包含列表框中的所有选定项目