首页 > 代码库 > C# dataGridView控件实用属性及事件总结

C# dataGridView控件实用属性及事件总结

一、属性

    1.控制时间字段只显示“年-月-日”:dataGridView1.Columns[10].DefaultCellStyle.Format = "yyyy-MM-dd";

    2.背景颜色:dataGridView1.BackgroundColor = Color.Red;

    3.列宽随内容自动调整:dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.AllCells;

    4.点击选中整行:dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

    5.隐藏最后一行无值记录:dataGridView1.AllowUserToAddRows = false;

    6.只读:dataGridView1.ReadOnly = true;

    7.隐藏某一列:dataGridView1.Columns[0].Visible = false;

二、事件

    1.添加序列

private void dataGridView2_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush brushOne = new SolidBrush(Color.Black);//定义一个颜色为红色的画刷
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, brushOne, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
         }

    2.添加右键菜单:

private void dataGridView2_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    if (e.ColumnIndex == -1) return;
                    if (dataGridView2.Rows[e.RowIndex].Selected == false)
                    {
                        dataGridView2.ClearSelection();
                        dataGridView2.Rows[e.RowIndex].Selected = true;
                    }
                    if (dataGridView2.SelectedRows.Count == 1)
                        dataGridView2.CurrentCell = dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }



C# dataGridView控件实用属性及事件总结