How to bind data in listview?

I usually use

gridview.Datasource=ds.Tables[0];

for my datagridview. How can I do this in listview?

Listview1.Datasource=ds

ds must be your datasouce or datatable

Interesting because when I pop open my trusty visual C# in VS and create a listView... it doesn't have a Datasource property.

Which, was also indicated in the link that pritesh supplied :) By the way, good link pritesh, perhaps a bit confusing for a beginner but the theory is all there.

Edit: Now THAT link, hirenpatel, is definitely going to do the trick as well :twisted:

Edited 6 Years Ago by Lusiphur: n/a

I've used this

{
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", con);
            da.Fill(ds);
            DataTable dt = new DataTable();
            dt = ds.Tables[0];

            listView1.Columns.Add("Student_No", 10, HorizontalAlignment.Left);

            foreach(DataRow dr in dt.Rows)
            {
                ListViewItem lvi = new ListViewItem(dr["Student_No"].ToString());
                lvi.Tag = dr;
                listView1.Items.Add(lvi);
            }
        }

But the listview is all mess up. The 270070032 student_no, goes something like '2700...', and it's mess up. How to fix this?

I've fixed it!

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", con);
            da.Fill(ds);
            DataTable dt = new DataTable();
            dt = ds.Tables[0];

            listView1.View = View.Details;
            listView1.GridLines = true;

            listView1.Columns.Add("Student_No", 150, HorizontalAlignment.Left);

            foreach(DataRow dr in dt.Rows)
            {
                ListViewItem lvi = new ListViewItem(dr["Student_No"].ToString());
                lvi.Tag = dr;
                listView1.Items.Add(lvi);
            }

Whenever I click the button, it doesn't clear the listview even though I have used this

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", con);
            da.Fill(ds);
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
[B]listView1.Items.Clear();[/B]

EDIT: The items are now being cleared by clearing the dataset also.
But the columns are being duplicated for every click. How to fix this?!

Edited 6 Years Ago by AngelicOne: n/a

It works now! Instead of .Items, I remove it and made it listView1.Clear() only.

Populate and clearing listview solved!

This question has already been answered. Start a new discussion instead.