0

I try to change ListView from other thread. I get an error: "Object of type System.String cannot be converted to type System.String[]". If I do not pass string[] as a parameter, the compliler will not compile the code. Do you have any idea what may be wrong?

public delegate void UpdateListView(string[] request);
public void UpdateComponents(string[] request)
{
    for (int j = 0; j < request.Length; j++)
    {
        switch (request[j])
        {
            case "ListViewSubnetworksChanged":
                if (listView1.InvokeRequired)
                {
                    UpdateListView d = new UpdateListView(UpdateComponents);
                    this.Invoke(d, request);
                }
                else
                {
                    listView1.Items.Clear();
                }
                break;
        }
    }
}
Jason Down
  • 21,731
  • 12
  • 83
  • 117

3 Answers3

0

The method is asking for an array so you can't pass it a string. If you only have one string you can create a new array containing that one string and call the method like this:

string val = "Data";
string[] arrayVal = new string[] { val };
UpdateComponents(arrayVal);

Or to simplify it to one line:

UpdateComponents(new string[] { val });
Kirlac
  • 684
  • 6
  • 18
0

There's nothing wrong. The compiler get's you syntax error cause you'er trying to give string as the param while the param that Invoke() needs is string[] You should give the data in a correct format that indicated. You can use STRING.ToArray() aggregate function to convert string to string[]

By the way, use foreach loop instead on for in these case that you want to iterating on data of a collection.

0

Reviewing your question and code, I don't understand why you would have that recursive call in place in the first place. I would simplify your code as follows:

private void UpdateComponents(string[] request)
{
    for (int j = 0; j < request.Length; j++)
    {
        switch (request[j])
        {
            case "ListViewSubnetworksChanged":
                ClearListViewItemsSafe();
                break;
        }
    }
}

private void ClearListViewItemsSafe()
{
    if (listView1.InvokeRequired)
    {
        this.Invoke(new Action(() => listView1.Items.Clear()));
    }
    else
    {
        listView1.Items.Clear();
    }
}

Additionally, that code block assumes that you actually have other case conditions that you are checking, and that you have some use for j in those other case blocks. If neither of those are true, I would recommend further optimizing the block as:

private void UpdateComponents(string[] request)
{
    foreach (string r in request)
    {
        if (r == "ListViewSubnetworksChanged")
        {
            ClearListViewItemsSafe();
            return;
        }
    }
}
Mike Guthrie
  • 4,029
  • 2
  • 25
  • 48