【问题标题】:How to bind a Boolean column to a toggle button in a DataGridView如何将布尔列绑定到 DataGridView 中的切换按钮
【发布时间】:2018-08-06 17:12:16
【问题描述】:

我有一个键入的 DataSet 和一个名为 Offset 的表。

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

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

【问题讨论】:

  • 看看this是否有帮助。

标签: c# winforms data-binding datagridview dataset


【解决方案1】:

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

示例

在表单上拖放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

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2015-10-02
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多