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();