C# DataGridView 使用

这篇博客详细介绍了如何在C#中操作DataGridView控件,包括设置标题和文本居中、隐藏行和列、调整行高、动态添加行、添加CheckBox列、为单元格赋值以及解决界面假死和清除选中状态的问题。通过这些技巧,可以更好地定制和优化DataGridView的显示和交互效果。

1、//dataGridView標題居中

dataGridView2.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

在这里插入图片描述

2、//dataGrideView文本居中

dataGridView2.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

3、//dataGridView 最後一行不顯示

 dataGridView2.AllowUserToAddRows = false;

在这里插入图片描述

4、//dataGridView 第一列不顯示

dataGridView2.RowHeadersVisible = false;

在这里插入图片描述

5、//設置行高
設置行高需要將DataGridView屬性中AutoSizeRowsMode設置為None.
在这里插入图片描述

dataGridView2.RowTemplate.Height = 100;

6、//增加行

 		for (int i = 0; i < 10; i++)
            {
                DataGridViewRow row = new DataGridViewRow();
                DataGridViewTextBoxCell textboxcell = new DataGridViewTextBoxCell();
                textboxcell.Value = "Cell["+i.ToString()+"]";
                row.Cells.Add(textboxcell);
                DataGridViewTextBoxCell textboxcel2 = new DataGridViewTextBoxCell();
                textboxcel2.Value = "";
                row.Cells.Add(textboxcel2);
                DataGridViewTextBoxCell textboxcel3 = new DataGridViewTextBoxCell();
                textboxcel3.Value = "mV";
                row.Cells.Add(textboxcel3);
                dataGridView2.Rows.Add(row);
            }

7、//DataGridView中添加CheckBox列(其他控件類似)

			DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();//添加一列,如果只需要一個用DataGridViewCheckBoxColumn
            checkBoxColumn.Name = "select2_Log";
            checkBoxColumn.HeaderText = "Log";	
            dataGridView2.Columns.Insert(3, checkBoxColumn);//3為第三列

在这里插入图片描述

8、給DataGridView中控件賦值

			for(int i=0;i<3;i++)
                    {
                        dataGridView3.Rows[i+4].Cells[1].Value = Temp[i].ToString();
                    }

最後效果圖
在这里插入图片描述

9、DataGridView界面假死

private void dataGridView_Transefer_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1); //增加序列号
            dataGridView_Transefer.CurrentCell = dataGridView_Transefer.Rows[this.dataGridView_Transefer.Rows.Count - 1].Cells[0];  //自动定位到最后一行
            dataGridView_Transefer.Update();    //解决假死现象
        }

7、DataGridView清除选中状态

private void dataGridViewProtect_SelectionChanged(object sender, EventArgs e)
{
    DataGridView dgv = sender as DataGridView;
    dgv.ClearSelection();
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值