winform DataGridView实现用shift多选checkbox

来源:互联网 发布:泰州网络推广 编辑:程序博客网 时间:2024/06/12 01:46

哈哈,谨以此文记住自己的一点笨方法

 

背景:winform,c#,Datagridview,checkbox 实现自由多选  保证DataGridview的MultiSelect属性值为true

 

代码中加入如下内容:

 

全局变量:

         private int startrow = -1;

 

以下是Datagridview的两个事件:

           private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
        {
            if (this.dataGridView1.SelectedCells.Count > 0 && e.KeyData == Keys.ShiftKey)
            {
                int endrow = this.dataGridView1.CurrentRow.Index;

                if (startrow <= endrow)
                {

                     //正序选时
                    for (int x = startrow; x <= endrow; x++)
                    {
                        this.dataGridView1.Rows[x].Cells["我的checkbox列"].Value = 1;
                    }
                }
                else
                {

                    //倒序选时
                    for (int x = endrow; x <= startrow; x++)
                    {
                        this.dataGridView1.Rows[x].Cells["我的checkbox列"].Value = 1;
                    }
                }
            }
        }

        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && !(Control.ModifierKeys == Keys.Shift  ))
            {
                if (this.dataGridView1.Focused && this.dataGridView1.CurrentCell.OwningColumn.DataPropertyName == "checkbox" && Convert.ToBoolean(this.dataGridView1.CurrentCell.EditedFormattedValue) == false)
                {
                    startrow = this.dataGridView1.CurrentRow.Index;
                }
            }
        }

 

 

ok啦,希望有帮助!!!