dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; //全部列自动适应
Dgv.Columns[0].AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;//某一列自动适应
//效果就是列宽会根据内容以及表头宽度自行判断,最后调整到合适的宽度。
dataGrid_bom.Rows[i].Cells[0].Value//取得指定行指定列的内容.
DataGridView1.Columns.Remove("Column1");
' 删除第一列
DataGridView1.Columns.RemoveAt(0);
' 删除第一行
DataGridView1.Rows.RemoveAt(0);
4) 删除选中行
[C#]
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
if (!r.IsNewRow)
{
DataGridView1.Rows.Remove(r);
}
}
// 禁止用户改变DataGridView1的所有列的列宽
DataGridView1.AllowUserToResizeColumns = false;
//禁止用户改变DataGridView1所有行的行高
DataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersVisible = false; //两种方法都可以
dataGridView_all.DataSource = DataTable.DefaultView;
//有时候dataGridView_all.DataSource = datatable发现数据不显示,这样就要加上DataTable.DefaultView;
//可见列的自动调整大小模式
dataGridView1.RowHeadersVisible = false; //不显示包含行标题的列。
dataGridView1.AutoGenerateColumns = false;//隐藏DataGridView控件中编辑列中没有的列名
让dataGridView1在头行显示行号<添加RowPostPaint事件,添加以下代码>
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 2).ToString(),
dataGridView1.RowHeadersDefaultCellStyle.Font,
rectangle,
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
//禁止DataGridView点击列标题排序
//在ColumnHeaderMouseClick事件中加入以下代码
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
方法一、DataGridView隔行显示不同的颜色
AlternatingRowsDefaultCellStyle 属性
获取或设置应用于 DataGridView 的奇数行的默认单元格样式。
RowsDefaultCellStyle 属性
获取或设置应用于 DataGridView 的行单元格的默认样式。
只需要增加以下代码即可实现隔行变色:
dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque;
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
、、============================================
方法二。
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 2).ToString(),
dataGridView1.RowHeadersDefaultCellStyle.Font,
rectangle,
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
if (e.RowIndex % 2 == 0||e.RowIndex==0) //背景颜色
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;
}
}