如何将布尔列绑定到DataGridView中的切换按钮

时间:2018-08-06 17:12:16

标签: c# winforms data-binding datagridview dataset

我有一个类型为DataSet的表,其中有一个名为Offset的表。

The Offset table

HoursMinutes是整数,并且IsNegativeBoolean.,我想将DataGridView绑定到该表,并且我希望{{ 1}}单元格看起来像一个按钮,每次单击该按钮时,其标签都会在“ +”和“-”之间切换。默认情况下,将表从“数据源”窗口拖到设计器图面上会为IsNegative生成DataGridViewCheckBoxColumn,如下所示:

DGV generated by dragging Offset

普通的CheckBox具有Appearance属性,可以将其设置为IsNegative,,使其看起来像切换按钮,但是DataGridViewCheckBoxColumn似乎没有具有同等性质;所以我想改用DataGridViewButtonColumn。我的问题是如何将其绑定到我的数据集。我需要处理哪些事件,如何知道要在DataTable中更改哪一行?我必须使用RowIndex之类的属性,还是有更可靠的方法?

1 个答案:

答案 0 :(得分:2)

您可以将列绑定到DataGridViewButtonColumn。然后使用以下事件满足要求:

enter image description here

示例

DataGridView拖放到表单上,并为表单粘贴以下代码并运行它:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    var dt = new DataTable();
    dt.Columns.Add("C1", typeof(bool)).DefaultValue = true;
    dt.Columns.Add("C2", typeof(string));
    dt.Rows.Add(true, "something");
    dt.Rows.Add(false, "something else");
    dataGridView1.Columns.Add(new DataGridViewButtonColumn()
    { DataPropertyName = "C1", Name = "C1", HeaderText = "C1" });
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()
    { DataPropertyName = "C2", Name = "C2", HeaderText = "C2" });
    dataGridView1.DataSource = dt;
    dataGridView1.CellFormatting += dgv_CellFormatting;
    dataGridView1.CellContentClick += dgv_CellContentClick;
}
private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex != 0)
        return;
    var value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
    if (value != null && value != DBNull.Value)
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !(bool)value;
}

private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex != 0)
        return;
    var value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
    if (value != null && value != DBNull.Value)
        e.Value = (bool)value ? "-" : "+";
}

注意

要更改列类型,只需编辑列即可(使用Columns属性或通过打开智能标签面板并选择“编辑列”)。然后在列编辑器对话框中,选中复选框列,然后在属性网格中将其ColumnType更改为DataGridViewButtonColumn