1 dataGridView属性设置
private void SetDgvStyle(DataGridView table)
{
try
{
table.ClearSelection();
table.MultiSelect = false;
table.AllowUserToAddRows = false;
table.AllowUserToDeleteRows = false;
table.AllowUserToResizeColumns = false;
table.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
table.AllowUserToResizeRows = false;
table.RowHeadersVisible = false;
table.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
table.CausesValidation = false;
table.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
table.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
table.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
table.ReadOnly = false;
table.RowHeadersWidth = 4;
table.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
table.RowTemplate.Height = 28;
table.ScrollBars = ScrollBars.Vertical;
table.TabStop = false;
table.VirtualMode = true;
dgv.Rows[lastTableHeadRow].Frozen = true;
for (var i = 0; i < table.Columns.Count; i++)
{
table.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
table.Columns[i].FillWeight = 1;
var column = table.Columns[i] as DataGridViewImageColumn;
if (column != null)
{
column.ImageLayout = DataGridViewImageCellLayout.Zoom;
}
}
}
catch (Exception)
{
}
}
2 以指定列排序
dataGridView.Sort(dataGridView.Columns[0], ListSortDirection.Descending);
3 实现鼠标右键选中行
private void dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.Button == MouseButtons.Right)
{
dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
}
}
}
4 选择复选框获取失效
dgv.CurrentCell = dgv.Rows[0].Cells[0];
DataTable dtCheck = (DataTable)dgv.DataSource;