Search code examples
c#sql-serverwinformslistviewitem

C# Cannot convert type 'System.Windows.Forms.ListViewItem' to 'my app.Users' class


I have a C# WinForms program accessing SQL server and querying data from it. I have two main classes: Users which contains the datatypes for the users that can log into the app, and Products which contains again the datatypes for the products that can be queried. Also I have a class that holds the methods for accessing the sql server. I made a function querying the users form the sql database into a list which than I load into a ListView lsv_MangageUsers. I was able to create the add new user and delete method, but when I started creating the modify user method I ran into a problem. Visual Studio says:

"Cannot convert type 'System.Windows.Forms.ListViewItem' to 'my app.Users' class".

I tried giving the selected item's value casting in Users class to the modify method and load into a new forms controls to allow the user to make modification on it. If I used method and function in a wrong order my apologies I am still new in C#. Any help would be appreciated.

The button's code that running the modify user method:

private void btn_ModifyUser_Click(object sender, EventArgs e)
{
    if (lsv_ManageUsers.FocusedItem.Index != -1)
    {
        UserNew userwindow = new UserNew((Users)lsv_ManageUsers.SelectedItems[0]);
        if (userwindow.ShowDialog() == DialogResult.OK)
        {
            LsvUsersRefresh();
            toolStripStatusLabel1.Text = "User successfully modified!";
        }
    }
}

Solution

  • The item referenced by lsv_ManageUsers.SelectedItems[0] is a ListViewItem, it is not one of your Users items, and you can't just cast from one to another because they are completely different things.

    If you want the world to work in this way then each ListViewItem has a Tag property that you are free to use for whatever purpose you feel like. Suggest adding the Users item to this property when you add the ListViewItem to the list, and then you can dereference it within your click handler.