Winform-DataGridView
1 常用属性
// 1.点击后的选中模式
this.dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
// 2.不显示首列
this.dgv.RowHeadersVisible = false;
// 3.设置单元格行高
this.dgv.RowTemplate.Height = 50;
// 4.设置是否显示列标题
this.dgv.ColumnHeadersVisible = false;
// 5.设置单个单元格的背景色 字体颜色
this.dgv.Rows[1].Cells[1].Style.BackColor = Color.Green;
this.dgv.Rows[1].Cells[1].Style.ForeColor = Color.Red;
// 6.隔行换颜色
this.dgv.RowsDefaultCellStyle.BackColor = Color.LightBlue;
this.dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.LightCyan;
// 7.设置列显示位置
this.dgv.Columns["ids"].DisplayIndex = 0;
// 8.列冻结
this.dgv.Columns["ids"].Frozen = true;
// 9.文本对其方式
// 10.列标题居中
this.dgv.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
// 11.单元格值为Null时的默认值
this.dgv.DefaultCellStyle.NullValue = "IsNull";
// 12.单元格边框样式
this.dgv.CellBorderStyle = DataGridViewCellBorderStyle.None;
// 13.数据样式
this.dgv.Columns["Price"].DefaultCellStyle.Format = "C3"; //货币格式,保留3位小数
// 14.取消多选
this.dgv.MultiSelect = false;
// 15.设置选中行
this.dgv.Rows[2].Selected = true;
// 17.选中单元格后的背景色
this.dgvO.DefaultCellStyle.SelectionBackColor = Color.Black;
2 常用方法
// 1.排序
this.dgv.Sort(dgv.Columns[3], ListSortDirection.Ascending);
// 2.当前单元格内容
string value = this.dgv.CurrentCell.Value.ToString();
3 添加列
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.Text = col.Name = "Delete";
col.UseColumnTextForButtonValue = true; // Button text 显示 Text值
this.dgv.Columns.Add(col); //添加到最后边
this.dgv.Columns.Insert(index,col); //添加到指定列
4 获取 DataGridViewCheckBoxColumn 选中项
注意:当添加DataGridViewCheckBoxColumn 列时,需要勾选 Enable Editing,否则不能选中
List<string> listIds = new List<string>();
for (int i = 0; i < dgv.Rows.Count; i++)
{
if (dgv.Rows[i].Cells[0].EditedFormattedValue.ToString().ToLower().Equals("true"))
{
listIds.Add(this.dgv.Rows[i].Cells["ids"].Value.ToString());
}
}
string str= string.Join(";", listIds.ToArray());
MessageBox.Show(str);
5 DataGridViewButtonColumn 列按钮点击事件
private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex <= -1) return; //异常处理,如果是第一行的话
if (this.dgv.Columns[e.ColumnIndex].HeaderText == "Delete")
{
string str = this.dgv.Rows[e.RowIndex].Cells["ids"].Value.ToString();
MessageBox.Show("Delete:" + str);
}
}
6 正常显示图片
//获取 Image类的实例,并修改图片的显示方式
DataGridViewImageColumn col = dgv.Columns["Image"] as DataGridViewImageColumn;
col.ImageLayout = DataGridViewImageCellLayout.Zoom;
//修改行高来设置高度
this.dgv.RowTemplate.Height = 60;
this.dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
7.换行显示
设置属性:
this.dgv.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
在需要换行的地方添加:Environment.NewLine