WinForm的DataGirdView判斷CheckBox是否被選中

首先咱們先設置下DataGirdView的列。this

而後啓動下編輯,就能夠選中與不選中了。在以後經過。spa

 #region 便利被選中的行,而後導出
        DataTable dtreport = new DataTable();
        public void LoadRows()
        {
            foreach (DataColumn dc in ((DataTable)dgvPrint.DataSource).Columns)
            {
                dtreport.Columns.Add(dc.ToString());
            }
            for (int i = 0; i < dgvPrint.Rows.Count; i++)
            {
                if ((bool)dgvPrint.Rows[i].Cells[0].EditedFormattedValue==true)
                {
                    //Bug   
                    DataRow dr = (dgvPrint.Rows[i].DataBoundItem as DataRowView).Row;
                    dtreport.Rows.Add(dr.ItemArray);
                }
            }
        }
        #endregion

選中全部的DataGridViewCheckbox須要這樣code

#region 選中全部
        private void CheckBoxAll_Click(object sender, EventArgs e)
        {
            for (int i=0;i<dgvPrint.Rows.Count;i++)
            {
                ((DataGridViewCheckBoxCell)this.dgvPrint.Rows[i].Cells[0]).Value = true;
            }
        }
        #endregion

 給DataTable添加一列 序號:orm

private DataTable AddSeriNumToDataTable(DataTable dt)
        {
            //須要返回的值
            DataTable dtNew;
            if (dt.Columns.IndexOf("序號") >= 0)
            {
                dtNew = dt;
            }
            else //添加一序號列,而且在第一列
            {
                int rowLength = dt.Rows.Count;
                int colLength = dt.Columns.Count;
                DataRow[] newRows = new DataRow[rowLength];

                dtNew = new DataTable();
                //在第一列添加「序號」列
                dtNew.Columns.Add("序號");
                for (int i = 0; i < colLength; i++)
                {
                    dtNew.Columns.Add(dt.Columns[i].ColumnName);
                    //複製dt中的數據
                    for (int j = 0; j < rowLength; j++)
                    {
                        if (newRows[j] == null)
                            newRows[j] = dtNew.NewRow();
                        //將其餘數據填充到第二列以後,由於第一列爲新增的序號列
                        newRows[j][i + 1] = dt.Rows[j][i];
                    }
                }
                foreach (DataRow row in newRows)
                {
                    dtNew.Rows.Add(row);
                }
            }
            //對序號列填充,從1遞增
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dtNew.Rows[i]["序號"] = i + 1;
            }
            return dtNew;
        }
相關文章
相關標籤/搜索