user3177511
user3177511

Reputation: 103

Error when using string.Join

I'am loading a text file and displaying the textfile name in a listbox. And when I click the listbox im saving the path of the file to a variable. This works in another application of mine, but in the new application I get the following error :

Error 8 The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments Error 9 Argument 2: cannot convert from 'System.Collections.Generic.IEnumerable' to 'string[]'

This is the code :

string fileloadpath;

private void FileListbox_SelectedIndexChanged(object sender, EventArgs e)
{
  var selectedItems = FileListbox.SelectedItems.Cast<FileItem>();                   

  var all = string.Join(Environment.NewLine, selectedItems.Select(x => x.Path1));

  fileloadpath = all;
}

Edit : I added ToArray() at the end and that fixed it. Thanks guys.

I have one more error related to this :

When I display the file path in the listbox, instead of the actual file name(test.txt), the text is displayed as : "OpenCV.Form1+FileItem"

Here is the code :

void reciperefresh()
   {
       FileListbox.Items.Clear();

       string[] files = Directory.GetFiles(@"C:\Recipe", "*.txt", 
          SearchOption.AllDirectories);

       foreach (string f in files)
       {
           var fileItem = new FileItem { Title1 = Path.GetFileName(f), 
            Path1 = Path.GetFullPath(f) };
           FileListbox.Items.Add(fileItem);

       }
   }

Upvotes: 0

Views: 1533

Answers (5)

Owen Pauling
Owen Pauling

Reputation: 11841

Select returns an IEnumerable but the method requires a string[]. Add ToArray after the Select.

var all = string.Join(Environment.NewLine, selectedItems.Select(x => x.Path1).ToArray());

Re: the additional part to your question (which should really be a new question), you need to change it to:

FileListbox.Items.Add(fileItem.Title1);

Otherwise it is using the Object.ToString() method which you are not overriding. Alternatively override the ToString method in your FileItem class.

Upvotes: 1

ankur goel
ankur goel

Reputation: 76

The error is self explanatory. It is saying to convert it to array of string.

Upvotes: 0

CodingNagger
CodingNagger

Reputation: 1528

The error is that you are trying to use an enumeration of string instead of a string array. Try that:

string.Join(Environment.NewLine, selectedItems.Select(x => x.Path1).ToArray());

Upvotes: 1

Samvel Petrosov
Samvel Petrosov

Reputation: 7696

Try to replace selectedItems.Select(x => x.Path1) with selectedItems.Select(x => x.Path1).ToArray(). You should pass an array of strings instead of IEnumerable<string>.

Upvotes: 2

NielsNet
NielsNet

Reputation: 828

You need to pass an Array or Strings instead of the Enumerable that your selectedElements are.

Upvotes: 1

Related Questions