在 Windows 窗体数据网格控件中添加单选按钮

3

图片描述在此

我有一个DataGrid控件在我的窗体上,我需要在运行时向它添加一行。 我有一个DataGrid列,需要在其中添加不同的UI控件(每个单元格都包含不同的UI控件,例如下拉框、复选框、超链接、单选按钮)。我可以添加其他控件,但无法添加单选按钮控件,如何将单选按钮添加到DataGrid列中? 我尝试使用这里的方法,但对于我来说并没有起作用,因为它要求整个列都是单选按钮列。


使用它的目的是什么?单选按钮用于在有几个选项时只选择一个选项。如果您只希望将其基于每行使用,则应使用复选框。 - MVCKarl
如果只有一个选项需要选择,我建议使用复选框。 - Rauld
我已经通过添加图片更新了问题,这就是我在网格中所需要的。 - nirav
1个回答

0

这里是如何将复选框列作为单选按钮的方法。从您的图片中可以看出,您需要一行所有列都作为单选按钮 -> 这更加复杂,取决于您如何将数据绑定到 datagridview。我更多地使用 VB.NET,所以这里可能会有一些语法错误...

在您的 datagridview 中创建一个 DataGridViewCheckBoxColumn 列 通过三个 DataGridView 事件,我的复选框列可以作为单选按钮工作

private Boolean bRbtnCurrentValue 
private Int32 iColumnRadioBtn = 4
private Datagridview dgv //Only for this exapmle

//In Event dgv_CellBeginEdit
{
    //Here we stored current value to variable
    if (this.dgv.CurrentCell.ColumnIndex = this.iColumnRadioBtn)
        this.bRbtnCurrentValue = this.dgv
}

//In Event dgv_CellEndEdit
{
    //Here we update if value changed
    Boolean bNewValue = this.dgv.CurrentCell.Value
    if (this.dgv.CurrentCell.ColumnIndex = this.iColumnRadioBtn)
    {
        if(bNewValue=False)
            this.dgv.CurrentCell.Value=this.bRbtnCurrentValue
        else
            //Here jo actions when value changed(database update etc.)
    }   
}

//Event dgv_ CurrentCellDirtyStateChanged
{
    if(this.dgv.CurrentCell.ColumnIndex = this.iColumnRadioBtn) andalso (dgv.IsCurrentCellDirty = True)
    {
        foreach(DataGridViewRow dgvr In dgv.Rows)
        {
            If (dgvr.Index = dgv.CurrentRow.Index)
                If (dgv.CurrentCell.Value = True)
                    dgv.CancelEdit() //True to False cannot be changed
            else
                If (dgvr.Cells(dgv.CurrentCell.ColumnIndex).Value=True)
                    dgvr.Cells(dgv.CurrentCell.ColumnIndex).Value = False
        }
    }
}

正如您所说,我应该创建DataGridViewCheckBoxColumn,但在我的应用程序中,该列还可以包含诸如组合框、文本框和超链接等控件。因此,我无法添加DataGridViewCheckBoxColumn,我想要将不同的控件添加到列的每个单元格中。 - nirav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接