Broken_Code
Broken_Code

Reputation: 306

Rows error help in listview function

Here is the code I am using.

foreach (DataRow row in data.Rows)
{
    ListViewItem lst = default(ListViewItem);
    lst = lvw.Items.Add(row(0));  // My error is on row

    for (int i = 1; i <= data.Columns.Count - 1; i++)
    {
        lst.SubItems.Add(row(i));
    }
}

Now, what I'm doing or trying to do is actually add database items onto my listview. However, I can't seem to get my rows onto my list view. I get a syntax error:

'Rows' is a 'variable' but is used like a 'method'.

I have been struggling with this winform for a couple days and my coding has stopped dead at this point. I have tried changing the parenthesis. Here is the whole function. I got it from the internet in vb.net and ran the code it worked. I then configured that code for my application in vb.net that worked too, now after converting to c# and it doesn't work which is my problem. I went through all the code(I am new to c# like relatively) and fixed most of it to work for my application except the row error

private void ShowDataInLvw(DataTable data, ListView lvw)
{       
    lvw.View = View.Details;
    lvw.GridLines = true;
    lvw.Columns.Clear();
    lvw.Items.Clear();
    foreach (DataColumn col in data.Columns)
    {
       lvw.Columns.Add(col.ToString());
    }
    foreach (DataRow row in data.Rows)
    {
        ListViewItem lst = default(ListViewItem);
        lst = lvw.Items.Add(row(0));

        for (int i = 1; i <= data.Columns.Count - 1; i++)
        {
            lst.SubItems.Add(row(i));
        }
    }  
}

Upvotes: 3

Views: 116

Answers (2)

Alex R.
Alex R.

Reputation: 4754

In C#, to get to an index of a collection, you need to use [ ] (whereas VB uses ( )). Refer to this specifically for DataRows.

Thus, your code should look like:

lst = lvw.Items.Add(row[0]);

And

lst.SubItems.Add(row[i])

On a side note, you may want to read up on the use of the default keyword.

EDIT:

Here's a complete listing (without spoon-feeding much), after noticing that your code won't actually work and assuming you really intend to do as described:

foreach (DataRow row in data.Rows)
{
    ListViewItem lst = default(ListViewItem);

    for (int i = 0; i <= data.Columns.Count - 1; i++)
    {
        if (i == 0)
           lst = new ListViewItem(row[0].ToString());
        else
           lst.SubItems.Add(row[i].ToString());
    }
    lvw.Items.Add(lst);
}

Notice a few things:

  • The instantiation of lst has been changed.
  • The lvw will add the lst along with its subitems.
  • The addition will occur only after the subitems have been created.

Disclaimer: I haven't tested the code, but the idea is there.

Upvotes: 2

Anthony Horne
Anthony Horne

Reputation: 2522

Have you tried:?

lst = lvw.Items.Add(row[0]);

lst.SubItems.Add(row[I]);

Upvotes: 1

Related Questions