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.
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?
The ListViewItem
itself represents the first column. Subsequent columns are represented by ListViewSubItem
s.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With