将选定的行gridview传递到另一个窗体上的另一个gridview
问题描述:
private void btnpass_Click(object sender, EventArgs e)
{
Inventory coo = new Inventory(dataGridView1.SelectedRows[0].Cells[0].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[1].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[2].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[3].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[4].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[5].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[6].Value.ToString());
coo.Show();
}
What I have tried:
Itried Pass selected row gridview to another gridview on another form but show error.
error is (Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index)
i use different method but not my problem solve
答
索引超出范围错误意味着您正在尝试从不存在的索引中读取值。为了避免这种例外,你在访问索引之前已经验证了..
Index out of range error means you are trying to read the value from an index which is not present. to avoid this exception you have validate before accessing the index..
private void button1_Click(object sender, EventArgs e)
{
var selectedRows = dataGridView1.SelectedRows;
if (selectedRows != null && selectedRows.Count > 0) // validate the index
{
DataGridViewCellCollection cells = selectedRows[0].Cells;
if (cells.Count >= 7) // validate the index
{
Inventory coo = new Inventory(
cells[0].Value.ToString(),
cells[1].Value.ToString(),
cells[2].Value.ToString(),
cells[3].Value.ToString(),
cells[4].Value.ToString(),
cells[5].Value.ToString(),
cells[6].Value.ToString());
coo.Show();
}
}
}