I copy then contents of a listbox to an array but it copies the value of the type name of the objects in the list instead of the value of the property in the object

Con Mari 40 Reputation points
2023-03-07T09:57:36.0233333+00:00

I m new to C# and visual studio

My promblem is the following:

In a form i have a list box and a text box

i have connected the listbox datasource property with an access database file and listbox displays all the contents of the database.

I want to copy the contents of the listbox to an array

I use the following command

 listbox1.Items.CopyTo(aa, 0); 

all the values of the array takes the value of the type name of the objects in the list instead of the value of the property in the object which is the following value:

System.Windows.Forms.ListBox + ObjectCollection

how can i take the actual value of the items of the listbox in my array. I really feel i m in a dead end

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,194 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,031 Reputation points
    2023-03-07T10:33:29.0766667+00:00

    Using the TableAdapter component will appear easy for novice coders but unless you study them they will present you with roadblocks time and time again.

    With that said, the trick is to work against the DataSource of the ListBox which is a BindingSource and the BindingSource DataSource is your DataSet.

    In the following example we cast accordingly to the productsBindingSource.DataSource to get at ProductsDataTable which is what is set to the ListBox (notice I don't even touch the ListBox here).

    form

    private void Form1_Load(object sender, EventArgs e)
    {
        productsTableAdapter.Fill(northWindDataSet.Products);
    
        string[] products = ((NorthWindDataSet)productsBindingSource.DataSource)
            .Products.Select(p => p.ProductName).ToArray();
    
        textBox1.Text = products[0];
    }
    

    Knowing this we can later assign the current item/product to the TextBox in a Button Click event.

    private void button1_Click(object sender, EventArgs e)
    {
        ProductsRow product = ((NorthWindDataSet)productsBindingSource.DataSource)
            .Products[productsBindingSource.Position];
    
        textBox1.Text = product.ProductName;
    }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful