'Search Listview using Textbox in C# from SQL Database

I use followng code in VB.Net to search data in listview using TextBox. This code was VB.NET i have changed this to C# according to my understanding as i am new to C# but this is not working.

private void TextBox1_TextChanged(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("Select * from Vendors Where VendorName Like'%" + TextBox1.Text + "%' or VendorID Like'%" + TextBox1.Text + "%'", con);
    SqlDataReader reader;
    con.Open();
    reader = cmd.ExecuteReader();
    cmd.Dispose();
    ListView1.Items.Clear();
    if (reader.HasRows)
    {
        while (reader.Read()) 
        {
            **ListView1.Items.Add(reader[0]);**
            ListView1.Items[ListView1.Items.Count - 1].SubItems.Add(reader.**item**[1]);
            ListView1.Items[ListView1.Items.Count - 1].SubItems.Add(reader.**Item**[2]);
            ListView1.Items[ListView1.Items.Count - 1].SubItems.Add(reader.Item[3]);
        }
    }
    reader.Close();
    con.Close();
}

i am getting error here ListView1.Items.Add(reader[0]) and here (reader.item[1]) (Where typed item of all 3 columns) could anyone point out correct this code. Thanks in advance.



Solution 1:[1]

From this point of view, I can see that you haven't created a object of ListViewItem class, and also here ListView1.Items.Add(reader[0]) you didn't cast your indexer,so maybe that is the reason why you got the error

So, first you need to create object of ListViewItem class, then add all of SubItems on that Item, and at the end you need to add that Item to your ListView1

It will be something like this

private void TextBox1_TextChanged(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("Select * from Vendors Where VendorName Like'%" + TextBox1.Text + "%' or VendorID Like'%" + TextBox1.Text + "%'", con);
    SqlDataReader reader;
    con.Open();
    reader = cmd.ExecuteReader();
    cmd.Dispose();
    ListView1.Items.Clear();
    if (reader.HasRows)
    {
        while (reader.Read()) 
        {

            ListViewItem item = new ListViewItem(reader[0].ToString()); // Or you can specify column name - ListViewItem item = new ListViewItem(reader["column_name"].ToString()); 
            item.SubItems.Add(reader[1].ToString());
            item.SubItems.Add(reader[2].ToString());
            item.SubItems.Add(reader[3].ToString());
            ListView1.Items.Add(item); // add this item to your ListView with all of his subitems
        }
    }
    reader.Close();
    con.Close();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakobson