首先我们先设置下DataGirdView的列。
然后启动下编辑,就可以选中与不选中了。在之后通过。
#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需要这样
#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添加一列 序号:
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;
}