Monday, October 27, 2008

Filling Windows Forms ListView with DataTable

If your are not familiar with List visit my blog Windows Forms ListView.

DataTable dt = new DataTable("Shalvin");
DataRow dr;
DataColumn dc;

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

listView1.Columns.Add("Blog", 170);
listView1.Columns.Add("Author", 170);

dc = new DataColumn("Blog");
dt.Columns.Add(dc);

dc = new DataColumn("Author");
dt.Columns.Add(dc);

dr= dt.NewRow();
dr["Blog"] = "http://weblogs.asp.net/Scottgu/";
dr["Author"] = "Scott Guthrie";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["Blog"] = "DotNetShalvin.blogspot.com";
dr["Author"] = "Shalvin";
dt.Rows.Add(dr);

listView1.Items.Clear();







To make things simple I am creating a DataTable and DataRows by code .Afterward I am iterating through the DataRows collection and adding it into ListView's SubItems collection.


private void Form1_Load(object sender, EventArgs e)
{
..
..
ListViewItem lvbl = new ListViewItem("Add new record");
listView1.Items.Add(lvbl);
}

private void listView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (listView1.FocusedItem.Text.ToString() == "Add new record")
MessageBox.Show("Add new record");
}

















VB .Net

Dim dt As New DataTable("Shalvin")
Dim dr As DataRow
Dim dc As DataColumn

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListView1.View = View.Details
ListView1.Columns.Add("Blog", 170)
ListView1.Columns.Add("Author", 170)

dc = New DataColumn("Blog")
dt.Columns.Add(dc)
dc = New DataColumn("Author")
dt.Columns.Add(dc)

dr = dt.NewRow()
dr("Blog") = "http://weblogs.asp.net/Scottgu/"
dr("Author") = "Scott Guthrie"
dt.Rows.Add(dr)

dr = dt.NewRow()
dr("Blog") = "DotNetShalvin.blogspot.com"
dr("Author") = "Shalvin"
dt.Rows.Add(dr)

For index As Integer = 0 To dt.Rows.Count - 1
Dim dr As DataRow = dt.Rows(index)
Dim lvi As New ListViewItem(dr("Blog").ToString())
ListView1.Items.Add(lvi)
lvi.SubItems.Add(dr("Author"))
Next


Related Blog :
DataTable DataColumn and DataRow (Asp .Net)

DataGridView - Extracting the Contents of Currently Selected Row



1 comment: