Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ListView Display

Tags:

c#

Guys i'm a beginner in implementing ListView in c#. I'm having a problem with these piece of code in c#.net. And I can't figure out whats happening in the control shown by the output. It seems i forgot something to give a value in properties of ListView Control.

2nd column values must appear on the first column.

enter image description here

This is my code:

using System;
using System.Collections.Generic;   
using System.ComponentModel;
using System.Data;                  
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;        
using System.Data.OleDb;            
namespace Database2
{
    public partial class Form1 : Form
    {
        OleDbConnection con;
        OleDbDataAdapter adapter;
        DataTable table;

        string conString = "Provider = Microsoft.Jet.OLEDB.4.0.; Data Source=DatabaseTest.mdb";
        string sqlQuery = "SELECT * FROM Person";

        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e){
            con = new OleDbConnection(conString);
            adapter = new OleDbDataAdapter(sqlQuery,conString);
            table = new DataTable();

            InitializeList();

            adapter.Fill(table);

            for (int i = 0; i < table.Columns.Count; i++)
                lstDisplay.Columns.Add(table.Columns[i].ColumnName.ToString(), lstDisplay.Width / 6-1);

            for (int i = 0; i < table.Rows.Count; i++) { 
                ListViewItem row = new ListViewItem();
               for (int j = 0; j < table.Columns.Count; j++)
                    row.SubItems.Add(table.Rows[i][j].ToString());
               lstDisplay.Items.Add(row);
            }
        }

        private void InitializeList() {
            lstDisplay.GridLines = true;
            lstDisplay.AllowColumnReorder = true;
            lstDisplay.LabelEdit = true;
            lstDisplay.FullRowSelect = true;
            lstDisplay.Sorting = SortOrder.Ascending;
            lstDisplay.View = View.Details;
        }
    }
}

Is there a listView property i forgot to give a value?

like image 688
Jed Avatar asked Feb 20 '23 17:02

Jed


1 Answers

The ListViewItem itself represents the first column. Subsequent columns are represented by ListViewSubItems.

Ex:

for (int i = 0; i < table.Rows.Count; i++)
{ 
   ListViewItem row = new ListViewItem(table.Rows[i][0].ToString());
   for (int j = 1; j < table.Columns.Count; j++)
      row.SubItems.Add(table.Rows[i][j].ToString());
   lstDisplay.Items.Add(row);
}
like image 104
Dave Cousineau Avatar answered Feb 27 '23 04:02

Dave Cousineau