0 votes

Make an array from a ListBox in C#

I have these data in the ListBox which I called bc:

ABCF
GHTP
HUJI

And this code:

bc = new String[lbReglas.Items.Count, lbReglas.Items[0].ToString().Split().Count()];
for (int i = 0; i < bc.GetLength(0); i++)
{
    for (int j = 0; j < bc.GetLength(1); j++)
    {
        bc[i, j] = Convert.ToString(lbReglas.Items[i].ToString().Split()[j]);
    }

}

What I find is an array of 3 rows by 1 column, and my problem is in the columns, what I want is that I be 3 rows by 4 columns(the number of columns depends on the size of the string that I enter), since the first string is ABCF... and I throw an array type:

bc[0,0]=A
bc[0,1]=B
bc[0,2]=C
bc[0,3]=F
bc[1,0]=G
bc[1,1]=H
bc[1,2]=T
bc[1,3]=P
bc[2,0]=H
bc[2,1]=U
bc[2,2]=J
bc[2,3]=I

Thank you!

0voto

Leandro Tuttini Points 25288

In the code you use Split() but didn't split for any character, you have to separate in some way.

string[,] bc = new string[lbReglas.Items.Count, 4];

for (int i = 0; i < bc.GetLength(0); i++)
{
    char[] letras = lbReglas.Items[i].ToString().ToCharArray();
    for (int j = 0; j < bc.GetLength(1); j++)
    {
        bc[i, j] = Convert.ToString(letras[j]);
    }

}

A string is basically a char[] so that you can take each letter without any split

C# | ToCharArray() Method

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X