Search code examples
c#.netemaillistboxselectedvalue

How to get multiple selectedvalues from listbox in c#?


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?


Solution

  • 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

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