SanyTiger
SanyTiger

Reputation: 666

Subitems and Column names in ListView not displayed

This is the code I'm working on

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
    SqlCommand cmd = new SqlCommand("select * from sometable", con);
    con.Open();
    SqlDataAdapter ada = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    ada.Fill(dt);

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        DataRow dr = dt.Rows[i];
        ListViewItem listitem = new ListViewItem(dr["Col1"].ToString()); // Value is 9999
        listitem.SubItems.Add(dr["Col2"].ToString()); // Value is 10 
        listitem.SubItems.Add(dr["Col3"].ToString()); // Value is 5

        listView1.Items.Add(listitem);
    }
}

But the output that I'm getting is of the order

enter image description here

Adding listView1.View = View.Details; to the code produces empty listview. How do I get an output that displays the column name and all values ?I'm oblivious to the mistake I'm doing. Any idea where I'm going wrong ?

Upvotes: 0

Views: 797

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

Try settings listView1.View to View.Details and add 3 proper columns to listView1.Columns in designer:

Here it is in designer

or in code:

listView.Columns.Clear();
listView.Columns.Add("Col1");
listView.Columns.Add("Col2");
listView.Columns.Add("Col3");

Then, add items this way:

listView.Items.Add(new ListViewItem(new[]
    {
        dr["Col1"].ToString(),
        dr["Col2"].ToString(),
        dr["Col3"].ToString()
    }));        

It always works for me. Your code may have produced an empty grid because you had no columns.

Upvotes: 4

Related Questions