DataGridView CheckBox单元格/列事件

时间:2012-11-13 01:16:56

标签: c# datagridview checkbox event-handling click

如何在DataGridView的CheckBoxColumn中订阅CheckBox的事件处理程序,类似于常规CheckBox的CheckChanged或Click事件处理程序?我有一个或多个列,在我的应用程序中的多个数据网格中,我想这样做。

我看过CellContentClick和CellClick,但它们似乎完全不优雅,因为它们会触发数据网格中的每一次点击,而不仅仅是感兴趣的Cell或CheckBox。

2 个答案:

答案 0 :(得分:3)

下面的解决方案来自于MSDN文档以及在这里和CodeProject上的一些切向线程中的一点运气。

我们的想法是创建一个派生自DataGridViewCheckBoxCell的类,该类包含一个与ContentClick一起触发的处理程序。对于一个DataGridView来说,这似乎有很多开销,但我的应用程序有许多DataGridViews,因此这段代码是可重用的,从而节省了时间。

/// <summary>
/// DataGridView cell class for check box cells with a OnContentClick event handler.
/// </summary>
public class DataGridViewEventCheckBoxCell : DataGridViewCheckBoxCell
{
    /// <summary>
    /// Event handler for OnContentClick event.
    /// </summary>
    protected EventHandler<DataGridViewCellEventArgs> ContentClickEventHandler { get; set; }

    /// <summary>
    /// Empty constructor. Required. Used by Clone mechanism
    /// </summary>
    public DataGridViewEventCheckBoxCell()
        : base()
    { }

    /// <summary>
    /// Pass through constructor for threeState parameter.
    /// </summary>
    /// <param name="threeState">True for three state check boxes, True, False, Indeterminate.</param>
    public DataGridViewEventCheckBoxCell(bool threeState)
        : base(threeState)
    { }

    /// <summary>
    /// Constructor to set the OnContentClick event handler.  
    /// Signature for handler should be (object sender, DataGridViewCellEventArgs e)
    /// The sender will be the DataGridViewCell that is clicked.
    /// </summary>
    /// <param name="handler">Handler for OnContentClick event</param>
    /// <param name="threeState">True for three state check boxes, True, False, Indeterminate.</param>
    public DataGridViewEventCheckBoxCell(EventHandler<DataGridViewCellEventArgs> handler, bool threeState)
        : base(threeState)
    {
        ContentClickEventHandler = handler;
    }

    /// <summary>
    /// Clone method override.  Required so CheckEventHandler property is cloned.
    /// Individual DataGridViewCells are cloned from the DataGridViewColumn.CellTemplate
    /// </summary>
    /// <returns></returns>
    public override object Clone()
    {
        DataGridViewEventCheckBoxCell clone = (DataGridViewEventCheckBoxCell)base.Clone();
        clone.ContentClickEventHandler = ContentClickEventHandler;
        return clone;
    }

    /// <summary>
    /// Override implementing OnContentClick event propagation 
    /// </summary>
    /// <param name="e">Event arg object, which contains row and column indexes.</param>
    protected override void OnContentClick(DataGridViewCellEventArgs e)
    {
        base.OnContentClick(e);
        if (ContentClickEventHandler != null)
            ContentClickEventHandler(this, e);
    }

    /// <summary>
    /// Override implementing OnContentDoubleClick event propagation 
    /// Required so fast clicks are handled properly.
    /// </summary>
    /// <param name="e">Event arg object, which contains row and column indexes.</param>
    protected override void OnContentDoubleClick(DataGridViewCellEventArgs e)
    {
        base.OnContentDoubleClick(e);
        if (ContentClickEventHandler != null)
            ContentClickEventHandler(this, e);
    }
}

因为我希望能够从列类引用这个单元类,所以我还实现了一个从DataGridViewCheckBoxColumn派生的类:

/// <summary>
/// DataGridView column class for a check box column with cells that have an OnContentClick handler.
/// </summary>
public class DataGridViewEventCheckBoxColumn : DataGridViewCheckBoxColumn
{
    /// <summary>
    /// Empty constructor.  Pass through to base constructor
    /// </summary>
    public DataGridViewEventCheckBoxColumn()
        : base()
    { }

    /// <summary>
    /// Pass through to base constructor with threeState parameter
    /// </summary>
    /// <param name="threeState">True for three state check boxes, True, False, Indeterminate.</param>
    public DataGridViewEventCheckBoxColumn(bool threeState)
        : base(threeState)
    { }

    /// <summary>
    /// Constructor for setting the OnContentClick event handler for the cell template.
    /// Note that the handler will be called for all clicks, even if the DataGridView is ReadOnly.
    /// For the "new" state of the checkbox, use the EditedFormattedValue property of the cell.
    /// </summary>
    /// <param name="handler">Event handler for OnContentClick.</param>
    /// <param name="threeState">True for three state check boxes, True, False, Indeterminate.</param>
    public DataGridViewEventCheckBoxColumn(EventHandler<DataGridViewCellEventArgs> handler, bool threeState)
        : base(threeState)
    {
        CellTemplate = new DataGridViewEventCheckBoxCell(handler, threeState);
    }
}

修剪掉多余的代码,我这样使用它:

public void AddCheckBoxColumn(DataGridView grid, EventHandler<DataGridViewCellEventArgs> handler, bool threeState)
{
   grid.Columns.Add(new DataGridViewEventCheckBoxColumn(handler, threeState));
}

可以删除列类,可以按如下方式使用:

public void AddCheckBoxColumn(DataGridView grid, EventHandler<DataGridViewCellEventArgs> handler, bool threeState)
{
   DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn(threeState);
   column.CellTemplate = new DataGridViewEventCheckBoxCell(handler, threeState);
   grid.Columns.Add(column);
}

这是一个示例事件处理程序。数据网格中另一列的状态将根据此列的值进行更新,并有条件地更新WasReleased属性中的某些状态信息。 DataGridView的DataSource是Specimen对象的集合,因此每行的DataBoundItem都是一个Specimen。 Specimen类是特定于应用程序的,但它具有此列显示的OnHold属性; IsReleased,由另一列显示;并被释放。

    public static void OnHoldCheckClick(object sender, DataGridViewCellEventArgs e)
    {
        if (sender is DataGridViewEventCheckBoxCell)
        {
            DataGridViewEventCheckBoxCell cell = sender as DataGridViewEventCheckBoxCell;

            if (!cell.ReadOnly)
            {
                // The rows in the DataGridView are bound to Specimen objects
                Specimen specimen = (Specimen)cell.OwningRow.DataBoundItem;
                // Modify the underlying data source
                if ((bool)cell.EditedFormattedValue)
                    specimen.IsReleased = false;
                else if (specimen.WasReleased)
                    specimen.IsReleased = true;
                // Then invalidate the cell in the other column to force it to redraw
                DataGridViewCell releasedCell = cell.OwningRow.Cells["IsReleased"];
                cell.DataGridView.InvalidateCell(releasedCell);
            }
        }
    }

好的样式可能会将事件处理程序中的一些代码推送到Specimen类中的方法中。

答案 1 :(得分:1)

你可以使用

e.Item.Cells [1]。文本

这里e是当前行和第二个单元格,记住单元格索引始终以0索引

开头