Reputation: 2664
I am using a DataGridView
to keep track of a List<myObject>
. To populate it, I use this foreach loop:
foreach (myObject object in myList)
{
if (object.Status == Status.Available)
{
myDataGridView.Rows.Add(object.Name, object.Status.ToString());
}
}
I then use an event to create a new form for the object in the selected row:
void myDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var index = myList[myDataGridView.CurrentRow.Index];
myForm form = new myForm(index);
}
So this works just fine until the status of an item in the list changes:
myList[10].Status = Status.Unavailable;
Now when myDataGridView
is updated, I can no longer use the row index to open the correct form for any row past 10. I'm at a loss as to what to do.
Can anybody tell me how to open the correct form even though the indices don't match up anymore?
EDIT: myList
holds characters in a game, some who are available for hire and some who aren't. I need myDataGridView
to only be populated with those whose status is Available
.
Upvotes: 0
Views: 51
Reputation: 570
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);
}
Upvotes: 0
Reputation: 2664
By modifying alabamasux' answer, I managed to get it working.
var index = myList[(int)myDataGridView.CurrentRow.Cells[2].Value];
myForm form = new myForm(index);
Upvotes: 1
Reputation: 1502
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
}
Upvotes: 0