Yuri Suzumiya
Yuri Suzumiya

Reputation: 33

How to show multiple Access database columns in a WinForms ListBox?

I have a simple access database that has an "ITEM ID" and an "ITEM NAME". Below is an example.

1 Sword

2 Axe

3 Cat

When trying to get this into my listBox using a query it displays "System.Data.DataRow". I have found ways to show the "ITEM ID" or "ITEM NAME" separately but not together as I desire.

If anyone could tell me how to make it show up "1 Sword" that would be great as I have been searching for answers for hours now.

private void RunQuery()
{
    errorMsg = "";
    q = SearchBoxItemsAll.Text;
    try
    {
        OleDbCommand cmd = new OleDbCommand(q, conn);
        OleDbDataAdapter a = new OleDbDataAdapter(cmd);

        DataTable dt = new DataTable();

        a.SelectCommand = cmd;
        a.Fill(dt);
        a.Dispose();

        listBox1.DataSource = dt;
    catch (Exception ex)
    {}
}

Right now I am using a query box to call the above hoping to make it display the results onto the listBox.

Also I am using WinForms in visual studio 2015 (required). I also don't want to use anything other than a listBox. Apart from this issue it has the look I want and does everything I need.

Upvotes: 0

Views: 633

Answers (2)

Amir Shrestha
Amir Shrestha

Reputation: 451

ListBox control does not support multi column display. Try ListView Control instead and add subitems

Upvotes: 0

Manu Varghese
Manu Varghese

Reputation: 811

Try this:

private void RunQuery()
{
    errorMsg = "";
    q = SearchBoxItemsAll.Text;
    try
    {
        OleDbCommand cmd = new OleDbCommand(q, conn);
        OleDbDataAdapter a = new OleDbDataAdapter(cmd);

        DataTable dt = new DataTable();

        a.SelectCommand = cmd;
        a.Fill(dt);
        a.Dispose();
       foreach(var v in dt.Rows)
       {                        
         listBox1.Items.Add(v[0].ToString()+" "+v[1].ToString());
       }
    }
    catch (Exception ex)
    {}
}

The better way to do it is by specifying DisplayMember and ValueMember and changing your SQL:

private void RunQuery()
{
    errorMsg = "";
    //q = SearchBoxItemsAll.Text;
    //Concatenate the ID and the Name in the SQL Query
    q = "SELECT [ITEM ID] , ([ITEM ID] +' '+ [ITEM NAME]) AS [ITEM NAME] FROM ITEMS";
    try
    {
        OleDbCommand cmd = new OleDbCommand(q, conn);
        OleDbDataAdapter a = new OleDbDataAdapter(cmd);

        DataTable dt = new DataTable();

        a.SelectCommand = cmd;
        a.Fill(dt);
        a.Dispose();
        listBox1.DisplayMember = "ITEM_NAME";
        listBox1.ValueMember = "ITEM_ID";
        listBox1.DataSource = dt;
    }
    catch (Exception ex)
    {}
}

Upvotes: 2

Related Questions