0

我正在使用 aDataGridView来跟踪 a List<myObject>。为了填充它,我使用了这个 foreach 循环:

foreach (myObject object in myList)
{
    if (object.Status == Status.Available)
    {
        myDataGridView.Rows.Add(object.Name, object.Status.ToString());
    }
}

然后我使用一个事件为所选行中的对象创建一个新表单:

void myDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    var index = myList[myDataGridView.CurrentRow.Index];
    myForm form = new myForm(index);
}

所以这工作得很好,直到列表中项目的状态发生变化:

myList[10].Status = Status.Unavailable;

现在myDataGridView更新时,我无法再使用行索引为超过 10 的任何行打开正确的表单。我不知道该怎么做。

即使索引不再匹配,谁能告诉我如何打开正确的表格?

编辑:myList在游戏中拥有角色,有些可以租用,有些则不能。我myDataGridView只需要填充状态为Available.

4

3 回答 3

1

通过修改 alabamasux 的答案,我设法让它工作。

var index = myList[(int)myDataGridView.CurrentRow.Cells[2].Value];
myForm form = new myForm(index);
于 2013-05-14T18:57:41.320 回答
0

I dont really see why doing it this way, when you can populate the gridview directly with the list you want with:

class TestObject { public string Code { get; set; } public string Text { get; set; } }

void PopulateGrid()
{
    TestObject test1 = new TestObject()
    {
    Code = "code 1",
    Text = "text 1"
    };
    TestObject test2 = new TestObject()
   {
    Code = "code 2",
    Text = "text 2"
    };
    List<TestObject> list = new List<TestObject>();
    list.Add(test1);
    list.Add(test2);

    dataGridView1.DataSource = list; //THIS IS WHAT SHOULD DO IT
}
于 2013-05-14T17:35:23.593 回答
0

Somehow you have to associate the index in your list with the row. One way you could do this is to have a hidden column in your grid that maintains the mapping between a row and the correct list index. To add a hidden column, modify your insert code as follows:

int i = 0;
foreach (myObject object in myList)
{
     if (object.Status == Status.Available)
     {
         myDataGridView.Rows.Add(object.Name, object.Status.ToString(), i);
     }

     i++;
}

//Hide the third column
myDataGridView.Columns[2].Visible = false;

Then during the CellDoubleClick event you can reference this hidden column to get the true index of the item in this row.

void myDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    int listIndex = (int)myDataGridView.CurrentRow.Cells[2].Value;

    var index = myList[listIndex];

    myForm form = new myForm(index);
}
于 2013-05-14T18:09:07.693 回答