簡體   English   中英

如何僅在DataGridView中選中兩個DataGridViewCheckBox列之一或為true

[英]How to have only one of two DataGridViewCheckBox columns checked or true in a DataGridView

我有一個定義了五列的DataGridView。 用戶通過運行時通過openFileDialog選擇一個或多個文件來填充DataGridView,並將文件名加載到DataGridView的第一列中。 第二和第三列包含用於指示應如何處理文件名的復選框。 真值為1,假值為0。但是,用戶只需要為每個文件名選擇兩個復選框之一。 如果用戶選中其中一個復選框,則我希望另一個復選框(如果已選中)變為未選中狀態。 這是下面的代碼。 它不會產生任何錯誤,並且當偶爾使一個復選框處於未選中狀態時被取消選中時,它可能會取消選中同一列或另一列中的另一個復選框,但永遠不會在同一行中。 我需要學習使用調試器,並且在陷入困境時現在可以進行調試,但是同時我也希望能收到以下任何幫助:

private void dataGridViewInputReports_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex > 0 && e.ColumnIndex < 3)
    {
        if (Convert.ToInt16(dataGridViewInputReports.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) == 1)
        {
            if (e.ColumnIndex == 1)
            {
                dataGridViewInputReports.Rows[e.RowIndex].Cells[2].Value = 0;
            }
            else if (e.ColumnIndex == 2)
            {
                dataGridViewInputReports.Rows[e.RowIndex].Cells[1].Value = 0;
            }
        }
    }
}

解決方案是不使用CellValueChanged事件,而是使用CellClick事件。 我在這里找到了該指南: https : //msdn.microsoft.com/zh-cn/library/system.windows.forms.datagridviewcheckboxcell(v=vs.110).aspx ,其中指出“如果您想在用戶單擊復選框單元格,可以處理DataGridView.CellClick事件,但是此事件在更新單元格值之前發生。如果單擊時需要新值,則一種方法是計算期望值根據當前值。” 因此,如果用戶單擊已選中的復選框(= 1),我必須編寫代碼,知道該復選框的值將變為未選中(= 0),但目前仍處於選中狀態(= 1)。 此代碼將切換在同一dataGridView行中選中兩個復選框中的哪個復選框:

private void dataGridViewInputFiles_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == 1 || e.ColumnIndex == 2)
    {
        if (Convert.ToInt16(dataGridViewInputFiles.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) == 0)
        {
            if (e.ColumnIndex == 1)
            {
                dataGridViewInputFiles.Rows[e.RowIndex].Cells[2].Value = 0;
            }
            else if (e.ColumnIndex == 2)
            {
                dataGridViewInputFiles.Rows[e.RowIndex].Cells[1].Value = 0;
            }
        }
        else
        {
            if (e.ColumnIndex == 1)
            {
                dataGridViewInputFiles.Rows[e.RowIndex].Cells[2].Value = 1;
            }
            else if (e.ColumnIndex == 2)
            {
                dataGridViewInputFiles.Rows[e.RowIndex].Cells[1].Value = 1;
            }
        }
    }
}

您可以參考此鏈接以了解如何對多個選擇進行操作。 這是用於刪除的多個選擇。 這可能對您的問題有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM