C#_dataGridView_表格的基本使用

C#_dataGridView_表格的基本使用

前言:表格就像是一个数据库一样的存在,在项目中应用非常多,显示内容少时可以使用TextBox,显示内容比较多时并且有一定规律时就可以是dataGridView非常方便。
注意:数据很多时不建议这样做(表格作为数据库),因为延时比较大,建议是在程序中创建一个二维数组进行存储数据会比较块。

1、表格的创建
2、表格内容的填充
3、表格中数据的获取
4、表格中Button点击事件
5、表格数据清除

表格的创建

从工具箱中拖拽dataGridView后进行表头的设计即可(最常用的方式)
在这里插入图片描述

表格内容的填充

接下来就是程序里面来填充表格数据

int count = 0;
foreach (var item in code)  //根据code这个对象来解析并把数据天填写在表格中
{
    int index = this.dataGridView1.Rows.Add();
    dataGridView1.Rows[index].Cells[0].Value = count++;  //编号每行加1
    dataGridView1.Rows[index].Cells[1].Value = item.streamId.ToString();
    dataGridView1.Rows[index].Cells[2].Value = item.ctrlType.ToString();
    dataGridView1.Rows[index].Cells[3].Value = item.param.type.ToString();
    dataGridView1.Rows[index].Cells[4].Value = item.tagId.ToString();
    dataGridView1.Rows[index].Cells[7].Value = "确认输入";
}
//Rows[index]表示行
//Cells[0]表示列

表格中数据的获取

//功能是将表格中第一行第三列中的16进制数(两字节)字符串存到数组data中去
if(dataGridView1.Rows[2].Cells[4].Value != null)
{
    data[5] = (byte)Convert.ToUInt16(dataGridView1.Rows[2].Cells[4].Value.ToString(), 16);
    data[6] = (byte)(Convert.ToUInt16(dataGridView1.Rows[2].Cells[4].Value.ToString(), 16) >> 8);  
}

表格中Button点击事件

表格中也可以添加按键事件

在这里插入图片描述

//点击确认输入的按钮会将对应行的设置值(四字节)转存到数组data中去
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)  //点击到了dataGridView第几行中的按钮
{
    DataGridViewButtonColumn checkCol = dataGridView1.Columns[e.ColumnIndex] as DataGridViewButtonColumn;
    if (checkCol != null)
    {
        if(dataGridView1.Rows[e.RowIndex].Cells[6].Value != null)
        {
            dataGridView1.Rows[e.RowIndex].Cells[5].Value = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
            data[9] = (byte)Convert.ToUInt32(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString());
            data[10] = (byte)(Convert.ToUInt32(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString()) >> 8);
            data[11] = (byte)(Convert.ToUInt32(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString()) >> 16);
            data[12] = (byte)(Convert.ToUInt32(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString()) >> 24);
        }
    }
}

表格数据清除

//一句话就可将表格清空
dataGridView1.Rows.Clear();
  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值