2018年6月9日 星期六

[C#]DataGridView新增全選功能

/// <summary>
/// Form Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form_Load(object sender, EventArgs e)
{
         ckBox.Text = "";
         ckBox.Checked = false;
         System.Drawing.Rectangle rect = dgvList.GetCellDisplayRectangle(0, -1, true);
         ckBox.Size = new System.Drawing.Size(13, 13);
         ckBox.Location = new Point(rect.Location.X + dgvList.Columns[0].Width / 2 - 13 / 2 - 1, rect.Location.Y + 3);
         ckBox.CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
         dgvList.Controls.Add(ckBox);
}

/// <summary>
/// 改變勾選狀態時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CheckBox_CheckedChanged(object sender, EventArgs e)
{
        for (int i = 0; i < dgvList.Rows.Count; i++)
        {
             dgvList.Rows[i].Cells["colIsCheck"].Value = ((CheckBox)sender).Checked;
         }
         dgvList.EndEdit();
}

沒有留言:

張貼留言