关闭自动生成列
dataGridView1.AutoGenerateColumns = false
绑定数据源
dataGridView1.DataSource = peoples
注意:绑定的数据源的公有字段不会显示,属性才可以显示
是否允许鼠标拖动列,以改变列的顺序
手动添加列头
格式化某一列的输出显示
private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//if (e.ColumnIndex == 2)
if (dataGridView2.Columns[e.ColumnIndex].Name == "sex")//推荐写法
{
switch (e.Value.ToString())
{
case "0":
e.Value = "男人";
e.CellStyle.ForeColor = Color.Blue;
break;
case "1":
e.Value = "女人";
e.CellStyle.ForeColor = Color.Red;
break;
default:
e.Value = "未知";
break;
}
}
}
单击单元格选中整行
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
不允许选中多行
dataGridView1.MultiSelect = false
删除选中行逻辑
private void btnDelete_Click(object sender, EventArgs e)
{
//获取选中的行
var rows = dataGridView1.SelectedRows;
if (rows.Count > 0)
{
DialogResult result = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.OK)
{
//int id = Convert.ToInt32(rows[0].Cells[0].Value);
int id = Convert.ToInt32(rows[0].Cells["id"].Value);//推荐
if (true)
{
//删除成功就重新绑定数据源
}
else
{
MessageBox.Show("删除失败");
}
}
}
else
{
MessageBox.Show("请先选中一行");
}
}
单击一行,把此行的值赋值给文本框
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
var row = dataGridView2.Rows[e.RowIndex];
txtName.Text = row.Cells[1].Value.ToString();//索引
txtName.Text = row.Cells["name"].Value.ToString();//列的name
}
}
取消选中的行
private void dataGridView2_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
dataGridView2.ClearSelection();
}
鼠标经过某一行,高亮显示
private void dataGridView2_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
this.dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightSkyBlue;
}
}
private void dataGridView2_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.RowIndex % 2 == 0)
{
//偶数行
this.dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = this.dataGridView2.RowsDefaultCellStyle.BackColor;
}
else
{
//奇数行
this.dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = this.dataGridView2.AlternatingRowsDefaultCellStyle.BackColor;
}
}
}
设置奇数行的背景色
dataGridView2.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(245, 245, 245)
设置行的背景色
dataGridView2.RowsDefaultCellStyle.BackColor = Color.Green