androidrill
androidrill

Reputation: 99

Insertion Of Data From Database Into ListView Control WindowForms

I am trying to select data from the database to listview, but it is not working .There are no errors or anything but the code is totally unresponsive.....

    private void Form1_Load(object sender, EventArgs e)
    {
        listView1.View = View.Details;
        listView1.GridLines = true;
        listView1.FullRowSelect = true;

        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();

        con.ConnectionString = @"Data Source=.;Initial Catalog=ListView_Data;Integrated Security=True";
        cmd.CommandText = @"select ProductName,Price,Quantity from producttable";
        con.Open();

        cmd.Connection = con;
        da.SelectCommand = cmd;
        da.Fill(dt);

        //////////////////////////////////////////////////////////////////////

        string[]ar=new string[100];

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ar[i] = dt.Rows[0][i].ToString();
        }
        ListViewItem itm = new ListViewItem(ar);

        listView1.Items.Add(itm);

    }

Upvotes: 0

Views: 83

Answers (2)

Steve
Steve

Reputation: 216293

You loop over all the rows and create an unique array that you try to use as a constructor for a single ListViewItem.

You could simplify your code with

foreach(DataRow d in dt.Rows)
    listView1.Items.Add(new ListViewItem(d.ItemArray.Select(x => x.ToString()).ToArray())); 

but this seems to be a classical case where you loop two times.

  • The first time, the call to DataAdapter.Fill loops over your results to fill a DataTable
  • The second time, you loop over the DataTable rows to fill the ListView.

With a small dataset there is no big concern, but if you return a large amount of data and you don't need to keep the DataTable for other purposes, then I suggest to use a SqlDataReader and prepare directly a ListViewItem without first filling a DataTable.

Upvotes: 1

Shell
Shell

Reputation: 6849

You can do like this.

string[]ar=new string[dt.Columns.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int c=0;c <dt.Columns.Count; c++)
        ar[c] = dt.Rows[i][c].ToString();

    listView1.Items.Add(new ListViewItem(ar));
}

But, I would like to preffer to use this.

ListViewItem li = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
    li = listView1.Items.Add(dt.Rows[i][0].ToString());
    for (int c = 1; c < dt.Columns.Count; c++)
        li.SubItems.Add(dt.Rows[i][c].ToString());
}

Upvotes: 1

Related Questions