列表到数组:Datagrid 中选定单元格的行、列索引

List to Array : Row, Column Indices of Selected Cells in Datagrid

我有 selected 单元格的列表,我希望将它们转换为数组以便保存。 我正在转换数组中的列表,以便我可以获得所有 selected 单元格的索引(连续的列),以便稍后检索以填充相同的单元格。

问题是因为单元格可以以随机方式 selected 即我可以 select 第 1 行第 1,2,3,7,8,9 列离开第 4,5,6 列 un select编辑。一旦遇到未 selected 索引,我就会收到“The Index was out of range”错误。 如果我 select 数据网格中间的某些东西会发生同样的错误,即不是 selecting 开始时的列,如第 1、2、3 列,而是 selecting 第 5 行第 5、6、7 列.

可能有人可以在这方面提供帮助,或者可能指出其他一些有效的方法来完成相同的任务。

List<DataGridViewCell> selectedCells = new List<DataGridViewCell>();

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
    if (selectedCells.Contains(cell) ) selectedCells .Remove(cell);
    else selectedCells .Add(cell);
    cell.Style.BackColor = selectedCells .Contains(cell) ? Color.Pink : Color.White;
}

private void buttonSaveButton_Click(object sender, EventArgs e)
{
    string [,] selectedcellsArray = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count];
    int i = 0;
    int j = 0;
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        while (j < dataGridView1.Columns.Count)
        {
            selectedcellsArray[i, j] = selectedCells[j].ColumnIndex.ToString();
            j++;
        }

        j = 0;
        i++; //next row
    } 
    //some more code
}

我不是 100% 确定,但我认为你最好改用 bool[,]

private void buttonSaveButton_Click(object sender, EventArgs e)
{
    bool [,] cellIsSelected = new bool[dataGridView1.Rows.Count, dataGridView1.Columns.Count];
    foreach(var selectedCell in selectedCells)
    {
        cellIsSelected[selectedCell.RowIndex,selectedCell.ColumnIndex] = true;
    }

    for(int i=0; i<dataGridView1.Rows.Count; i++)
    {
        for(int j=0; j<dataGridView1.Columns.Count; j++)
        {
            //determine if the cell at postion i,j is selected
            if(cellIsSelected[i,j])
            {
                //It is selected.
            }
        }
    }
}

但如果这样可行,您最好只跟踪它而不是选定单元格的列表(除非您在其他地方使用它们)。此外,这将假设 dataGridView 具有一定数量的行和列。

bool[,] cellIsSelected = new bool[dataGridView1.Rows.Count, dataGridView1.Columns.Count];

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    cellIsSelected[e.RowIndex, e.ColumnIndex] = !cellIsSelected[e.RowIndex, e.ColumnIndex];
    cell.Style.BackColor = cellIsSelected[e.RowIndex, e.ColumnIndex] ? Color.Pink : Color.White;
}