0

I'm trying to add selected values from list box to array or list and I'm getting a strange error

here is my code

private void button3_Click(object sender, EventArgs e)
        {
            List<string> _AttName = new List<string>();
            for (int _i = 0; _i < listBox1.SelectedItems.Count; _i++)
            {

                if (listBox1.SelectedItem != null)
                {
-> Failes here ->   _AttName.Add(listBox1.SelectedValue.ToString());
                    listBox1.SetSelected(listBox1.SelectedIndex, false);

                }
            }
        }

or

private void button3_Click(object sender, EventArgs e)
        {
            string[] _AttName = new string[listBox1.SelectedItems.Count];
            for (int _i = 0; _i < listBox1.SelectedItems.Count; _i++)
            {

                if (listBox1.SelectedItem != null)
                {
                    _AttName[_i] = listBox1.SelectedValue.ToString();
                    listBox1.SetSelected(listBox1.SelectedIndex, false);

                }
            }
        }

here is the error I get enter image description here

Light_User
  • 83
  • 2
  • 11

2 Answers2

1

Problem : you will get this error because while binding the Items into the ListBox you have only binded the DisplayMemeber but not ValueMember.

So you don't have any Value associated to the Items in the ListBox.

Solution : you can use SelectedItem property to get the Item.

Replace This:

_AttName.Add(listBox1.SelectedValue.ToString());

With This:

_AttName.Add(listBox1.SelectedItem.ToString());
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
0

Try this:

   if (listBox1.SelectedItem != null && listBox1.SelectedValue != null)
   {

         _AttName.Add(listBox1.SelectedValue.ToString());
         listBox1.SetSelected(listBox1.SelectedIndex, false);
   }

Other solution:(Instead of using ToString(), use Convert.ToString())

   if (listBox1.SelectedItem != null)
   {
         _AttName.Add(Convert.ToString(listBox1.SelectedValue)); // Convert.ToString() will handle the null.
         listBox1.SetSelected(listBox1.SelectedIndex, false);
   }
Usman Khalid
  • 3,032
  • 9
  • 41
  • 66