I m trying to copy the items of a listbox to an array and the array gets the values of the type name of the objects in the list instead of the value of a property in the object.

Con Mari 40 Reputation points
2023-03-07T09:33:42.8766667+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

This is my whole code

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace food1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void pRODUCTSBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.pRODUCTSBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.foodsDataSet);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'foodsDataSet.PRODUCTS' table. You can move, or remove it, as needed.
            this.pRODUCTSTableAdapter.Fill(this.foodsDataSet.PRODUCTS);     
         
            object[] aa = new object[80];                   
            listbox1.Items.CopyTo(aa, 0);                           
            textBox1.Text = aa[1];          
        }
                     
    }
}

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,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2023-03-07T12:18:30.74+00:00

    Check this:

    string[] aa = listbox1.Items.Cast<object>( ).Select( z => listbox1.GetItemText( z ) ).ToArray( );
    

    and this:

    textBox1.Text = listbox1.GetItemText( listbox1.Items[1] );  
    

    However, if you are using data binding, maybe it is also possible to get the strings from the data source.


0 additional answers

Sort by: Most helpful