6

我有一个应用程序,WinForms我在列表框中插入名称和价格。名称和价格分别存储在二维数组中。现在,当我从中选择一条记录时,listbox它只给了我一个索引,我可以从中获取字符串名称和价格来更新该记录,我必须为此更改该索引处的名称和价格,我想同时更新二维数组名称和价格。但是选择的索引只是一维的。我想将该索引转换为行和列。怎么做?

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

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);
    }
}
4

4 回答 4

39

虽然我没有完全理解确切的场景,但在 1D 和 2D 坐标之间转换的常用方法是:

从二维到一维:

index = x + (y * width)

或者

index = y + (x * height)

取决于您是从左到右还是从上到下阅读。

从一维到二维:

x = index % width
y = index / width 

或者

x = index / height
y = index % height
于 2013-05-28T11:19:09.067 回答
2

用于将 1D 索引转换为 3D 索引和从 3D 索引转换:

(int, int, int) OneToThree(i, dx, dy int) {
    z = i / (dx * dy)
    i = i % (dx * dy)
    y = i / dx
    x = i % dx
    return x, y, z
}

int ThreeToOne(x, y, z, dx, dy int) {
    return x + y*dx + z*dx*dy
}
于 2019-02-21T15:05:07.967 回答
0

试试这个,

int i = OneDimensionIndex%NbColumn
int j = OneDimensionIndex/NbRow //Care here you have to take the integer part
于 2013-05-28T11:17:45.673 回答
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;
于 2013-05-28T11:17:50.033 回答