7

I have one application of WinForms which inside list box I am inserting name and price..name and price are stored in two dimensional array respectively. Now when I select one record from the listbox it gives me only one index from which I can get the string name and price to update that record I have to change name and price at that index for this I want to update both two dimensional array name and price. but the selected index is only one dimensional. I want to convert that index into row and column. How to do that?

But I'm inserting record in list box like this.

int row = 6, column = 10;
for(int i=0;i<row;i++)
{
    for(int j=0;j<column;j++)
    {
        value= row+" \t "+ column +" \t "+ name[i, j]+" \t " +price[i, j];
        listbox.items.add(value);
    }
}
Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
Aabha
  • 304
  • 1
  • 2
  • 12

3 Answers3

42

While I didn't fully understand the exact scenario, the common way to translate between 1D and 2D coordinates is:

From 2D to 1D:

index = x + (y * width)

or

index = y + (x * height)

depending on whether you read from left to right or top to bottom.

From 1D to 2D:

x = index % width
y = index / width 

or

x = index / height
y = index % height
BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
0

Try this,

int i = OneDimensionIndex%NbColumn
int j = OneDimensionIndex/NbRow //Care here you have to take the integer part
Leep
  • 447
  • 1
  • 3
  • 11
  • This is correct if the source array contains a sequence like `name price name price ...`. This, however, is not a real two-dimensional array. – Thorsten Dittmar May 28 '13 at 11:18
0

Well, if I understand you correctly, in your case, obviously the index of the ListBox entry's array entry is the index in the ListBox. The name and price are then at index 0 and index 1 of that array element.

Example:

string[][] namesAndPrices = ...;

// To fill the list with entries like "Name: 123.45"
foreach (string[] nameAndPrice in namesAndPrices)
   listBox1.Items.Add(String.Format("{0}: {1}", nameAndPrice[0], nameAndPrice[1]));

// To get the array and the name and price, it's enough to use the index
string[] selectedArray = namesAndPrices[listBox1.SelectedIndex];
string theName = selectedArray[0];
string thePrice = selectedArray[1];

If you have an array like that:

string[] namesAndPrices = new string[] { "Hello", "123", "World", "234" };

Things are different. In that case, the indices are

int indexOfName = listBox1.SelectedIndex * 2;
int indexOfPrice = listBox1.SelectedIndex * 2 + 1;
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139