2
string[] chkItems = new string[4];    
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
itemCount = ltbxInterests.SelectedItems.Count;
for (int i = 0; i <= itemCount; i++)
{
  ltbxInterests.SelectedItems.CopyTo(chkItems, 0); 
  // here it is returning an exception 
  //"Object cannot be stored in an array of this type."
}

Please help me how to get out from this exception

1
  • What's the type of chkItems ? Commented Jul 21, 2011 at 6:44

3 Answers 3

2

Couple issues here, chkItems is defined as length 4 so you will get an exception if you try and put more than 4 items in. The source array SelectedItems is of type object so you would need to cast the result.

Assuming you are only putting strings into the listbox you could use (remember to reference System.Linq)

string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;

string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().ToArray();

If you are wanting to limit to the first 4 items, you could replace the last line to

string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().Take(4).ToArray();

Also you could shorten the code to use an array initializer (but this wil make str length 3 because you only have 3 items):

string[] str = new [] {
  txtID.Text,
  txtName.Text,
  txtEmail.Text,
}
Sign up to request clarification or add additional context in comments.

Comments

1

SelectedItems is a collection of Object, then, in order to use CopyTo methods, chkItems must be an array of type object (i.e. object[]).

Otherwise, you can use LINQ to convert, for example, to a list of strings:

var selectedList = ltbxInterests.SelectedItems.OfType<object>()
                                              .Select(x => x.ToString()).ToList();

Comments

0

You chould check the Type of > chkItems .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.