using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace Samples
{
public partial class General : Form
{
public General()
{
InitializeComponent();
}
myColHeader hCell;
private void General_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("status",typeof(bool));
dt.Rows.Add(true);
dt.Rows.Add(false);
dt.Rows.Add(true);
dt.Rows.Add(false);
dt.Rows.Add(true);
this.dataGridView1.DataSource = dt;
hCell = new myColHeader();
this.dataGridView1.Columns[0].HeaderCell = hCell;
}
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == 0)//the checkbox col
{
for (int j = 0; j < this.dataGridView1.Rows.Count - 1; j++)
{
this.dataGridView1.Rows[j].Cells[0].Value = hCell.CheckAll;
}
}
}
}
class myColHeader:DataGridViewColumnHeaderCell
{
private Rectangle CheckBoxRegion;
private bool checkAll = false;
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
graphics.FillRectangle(new SolidBrush(cellStyle.BackColor), cellBounds);
CheckBoxRegion = new Rectangle(
cellBounds.Location.X+1,
cellBounds.Location.Y+2,
25, cellBounds.Size.Height-4);
if (this.checkAll)
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked);
else
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal);
Rectangle normalRegion =
new Rectangle(
cellBounds.Location.X + 1 + 25,
cellBounds.Location.Y,
cellBounds.Size.Width - 26,
cellBounds.Size.Height);
graphics.DrawString(value.ToString(), cellStyle.Font, new SolidBrush(cellStyle.ForeColor), normalRegion);
}
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
//Convert the CheckBoxRegion
Rectangle rec = new Rectangle(new Point(0,0),this.CheckBoxRegion.Size);
this.checkAll = !this.checkAll;
if (rec.Contains(e.Location))
{
this.DataGridView.Invalidate();
}
base.OnMouseClick(e);
}
//Property
public bool CheckAll
{
get { return this.checkAll; }
set { this.checkAll = value; }
}
}
}
No comments:
Post a Comment