Gold
Gold

Reputation: 62424

how to see ListBox like DataGridView ? (connect ListBox to DataBase)

how i can see ListBox like DataGridView ?

i want to connect ListBox to any DataBase and see it like DataGridView.

thank's in advance

Upvotes: 1

Views: 3603

Answers (1)

MusiGenesis
MusiGenesis

Reputation: 75296

You need to use a ListView instead of a ListBox. To make a ListView look like a DataGridView, you need to set its View property to Details, its HeaderStyle to Clickable or Nonclickable, and then add one or more ColumnHeaders to its Columns collection (you can do this easily from the properties windows, or add them in code). You would generally add one column header for each field of data from the database table you wish to display.

Assuming that you have a DataTable named dt filled with the data you wish to display, you would add it to a ListView named listView1 with code somewhat like this:

foreach (DataRow row in dt.Rows)
{
    ListViewItem item = new ListViewItem(
        new string[] {
            row["FirstName"].ToString(),
            row["LastName"].ToString(),
            row["Age"].ToString()});
    lv.Items.Add(item);
}

For this example code to work correctly, you would add three ColumnHeaders to the Columns collection ("First Name", "Last Name" and "Age" - note that the text of the column headers does not have to exactly match the field names in the DataTable).

However, you might have an easier time just using a DataGridView for this, since it can be quickly and simply bound to a DataTable without any code like this.

Upvotes: 2

Related Questions