2013-05-28 70 views
-1

我有一个WinForms的应用程序,里面的列表框中我插入名称和价格..名称和价格分别存储在二维数组中。现在,当我从listbox中选择一条记录时,它只给出一个索引,我可以从中获取字符串名称和价格以更新该记录,因此我必须更改该索引的名称和价格,以便我更新两个二维数组名称和价格。但选定的指标只有一个维度。我想将该索引转换成行和列。怎么做?将一维数组的索引转换为二维数组i。即行和列

但我在这样的列表框中插入记录。

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); 
    } 
} 
+1

你或许应该发布一些代码.... –

回答

6

虽然我没有完全理解确切的情况下,常用的方法1D之间进行转换和二维坐标是:

从2D到1D:

index = x + (y * width) 

index = y + (x * height) 

取决于你是否从左至右或从上到下阅读。

从一维到二维:

x = index % width 
y = index/width 

x = index/height 
y = index % height 
+0

非常感谢它.. – Aabha

+0

如何做到多维数组? – Vlad

0

试试这个,

int i = OneDimensionIndex%NbColumn 
int j = OneDimensionIndex/NbRow //Care here you have to take the integer part 
+0

这是正确的,如果源数组包含像'名称价格名称价格序列...'。但是,这不是一个真正的二维数组。 –

0

好吧,如果我理解正确的话,在你的情况下,ListBox条目的数组项的明显的指标是在ListBox索引。然后名称和价格位于该数组元素的索引0和索引1

例子:

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]; 

如果你有这样的一个数组:

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

事情是不同的。在这种情况下,指数

int indexOfName = listBox1.SelectedIndex * 2; 
int indexOfPrice = listBox1.SelectedIndex * 2 + 1; 
+0

如何更改添加源代码相关部分的问题?这是*不是*的东西要张贴在评论。 –

相关问题