Jyoti Pawar
Jyoti Pawar

Reputation: 29

how to retrieve data table in the form of table into the listbox

i am creating an application of extracting excel in to data table which will display in to list ox. but problem is all the data comes row wise data into list box.

DataTable dt = new DataTable();
DataSet ds = new DataSet();
DataTable sheet = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,  null);
OleDbCommand selectCmd = new OleDbCommand(String.Format("SELECT * FROM   [{0}]", sheet.Rows[0]["TABLE_NAME"]), dbConn);
OleDbDataAdapter dbAdapter = new OleDbDataAdapter(selectCmd);
dbAdapter.Fill(dt);


foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn col in dt.Columns)
    {
        ListBox1.Items.Add(row[col].ToString());
    }
}

Upvotes: 0

Views: 437

Answers (1)

JonPall
JonPall

Reputation: 814

Why don´t you just use the DataGridView class? Then just can set the DataTable as data source directly.

dataGridView1.DataSource = dt;

For a listbox, you'll need to create a string representing each column. Which will be hard to align. And if you would want to modify the cell values it would be quite cumbersome.

foreach (DataRow row in dt.Rows)
{
    var sb = new StringBuilder();
    foreach (DataColumn col in dt.Columns)
    {
        sb.Append(row[col] + "\t");
    }
    ListBox1.Items.Add(sb.ToString());
}

Upvotes: 1

Related Questions