DataGridView復選框實現全選功能,並取被選中的某行某列的值(三)


目標:

一、選中全選這個復選框,會選中第一列所有的復選框

 拉過來一個CheckBox控件(CheckBox1)覆蓋在第一列的標題上,文本值:全選

 

方法:雙擊上面拉的CheckBox控件,進入其事件

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            int count = dataGridView1.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];
                Boolean flag = Convert.ToBoolean(checkCell.Value);
                if (flag == false)
                {
                    checkCell.Value = true;
                }
                else
                {
                    continue;
                }
            }
        }

即可實現:

 

 取被選中的那一行的某列的值:

       string aaa= "";
            int count = dataGridView1.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];
                Boolean flag = Convert.ToBoolean(checkCell.Value);
                if (flag == true)
                {
                    aaa= this.dataGridView1.Rows[i].Cells[2].Value.ToString(); 
                } 
            }

 

 

這就是取被選中的那一行的第三列的值

 

目標:

二、取消所有選中的復選框,CheckBox1未選中的情況下,取消第一列所有已選中的

 

方法:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                int count = dataGridView1.Rows.Count;
                for (int i = 0; i < count; i++)
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];
                    Boolean flag = Convert.ToBoolean(checkCell.Value);
                    if (flag == false)
                    {
                        checkCell.Value = true;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            else
            {
                int count = dataGridView1.Rows.Count;
                for (int i = 0; i < count; i++)
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];
                    Boolean flag = Convert.ToBoolean(checkCell.Value);
                    if (flag == true)
                    {
                        checkCell.Value = false;
                    }
                    else
                    {
                        continue;
                    }
                }

            }


        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM