C# Windows - DataGridViewComboBoxCell 未从 DataGridView 中清除

问题描述 投票:0回答:1

我正在使用 VS 2022 C# Windows。

我有一个 DataGridView,它将显示一个 DataGridViewComboBoxCell,具体取决于所选的列。

    private void dgv_CurrentCellChanged(object sender, EventArgs e)
    {
        // Not Form Just Loaded and CurrentCell Not Null
        if ((!Form_Just_Loaded) && (dgv.CurrentCell != null))
        {
            int Col = dgv.CurrentCell.ColumnIndex;
            int Row = dgv.CurrentCell.RowIndex;

            switch (Col)
            {
                case Con_Day_Of_Week_Col:
                    {
                        // If the Focus is in the Day of The week Column then set to the next Cell
                        break;
                    }   
                case Con_Company_Col:
                    {
                        // If the Focus is in the Company Name Column then create the combobox and display
                        DataGridViewComboBoxCell myCell = (DataGridViewComboBoxCell)dgvTimeSheet.Rows[Row].Cells[Col];
                        myCell.Items.Clear();
                        for (int m = 0; m < Con_Companys.Length; m++)
                        {
                            myCell.Items.Add(Con_Companys[m]);
                        }
                        // Open the Combobox
                        SendKeys.Send("{F4}");
                        break;
                    }
            }                   
        }
    }

这个效果很好。

清除行时,DataGridViewComboBoxCell 仍然可见,并且在使用 ContextMenuStrip|ToolStripMenuItem 时不起作用。

    private void tsmiClear_Row_Click(object sender, EventArgs e)
    {
        int Selected_Row = dgvTimeSheet.CurrentRow.Index;

        for (int i = Con_Normal_Hours_Col; i < dgvTimeSheet.ColumnCount; i++)
        {
            dgvTimeSheet.Rows[Selected_Row].Cells[i].Value = "";
        }
    }

如果我从 Button 调用 ContextMenuStrip|ToolStripMenuItem 事件,它会起作用,清除 DataGridViewComboBoxCell。

    private void btnClear_Row_Click(object sender, EventArgs e)
    {
        tsmiClear_Row_Click(sender, e);
    }

为什么如果我使用按钮事件,DataGridViewComboBoxCell 会被清除,而使用 ContextMenuStrip|ToolStripMenuItem 事件时不会被清除?

谢谢

c# contextmenustrip datagridviewcombobox
1个回答
0
投票

我发现的唯一方法是将 DataGridView 上的焦点设置到同一行但不是 DataGridViewComboBoxCell 的单元格。

private void tsmiClear_Row_Click(object sender, EventArgs e)
{
    int Selected_Row = dgvTimeSheet.CurrentRow.Index;
    
    dgvTimeSheet.Rows[Selected_Row].Cells[Con_Normal_Hours_Col].Selected = true;
    
    for (int i = Con_Normal_Hours_Col; i < dgvTimeSheet.ColumnCount; i++)
    {
        dgvTimeSheet.Rows[Selected_Row].Cells[i].Value = "";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.