上位机学习记录(9) 表格控件的行与列动态添加与表格的扁平化处理
上位机学习记录(9) 表格控件的行与列动态添加与表格的扁平化处理
- 表格的扁平化处理
运行时效果:
-
将图片动态加入到表格中
运行时效果:
鼠标悬停时:表现为红色的地方,能看到相关信息
同时也支持双击打开,进行查看相关信息
编写流程如下:
第一步:
this.dgv_data.AutoGenerateColumns = false;
this.Load += FrmMonitor_Load;
第二步:
private List<RowState> GetCurrentRowState()
{
/// 存放每个点的数据
List<ActualStoreData> data = ActualStoreDataService.GetActualStoreData();
/// 每一行的情况
/// RowState 带有行号 00-09列 所以使用十列就能表示100个位置是否被占用
List<RowState> stateList = new List<RowState>();
if (data.Count >= RowCount * ColumnCount)
{
for (int i = 0; i < RowCount; i++)
{
RowState state = new RowState()
{
RowIndex = i,
Column01 = data[ColumnCount * i].StoreState,
Column02 = data[ColumnCount * i + 1].StoreState,
Column03 = data[ColumnCount * i + 2].StoreState,
Column04 = data[ColumnCount * i + 3].StoreState,
Column05 = data[ColumnCount * i + 4].StoreState,
Column06 = data[ColumnCount * i + 5].StoreState,
Column07 = data[ColumnCount * i + 6].StoreState,
Column08 = data[ColumnCount * i + 7].StoreState,
Column09 = data[ColumnCount * i + 8].StoreState,
};
stateList.Add(state);
}
return stateList;
}
return null;
}
第三步:
private void FrmMonitor_Load(object sender, EventArgs e)
{
//初始化
//先添加第一列
DataGridViewTextBoxColumn header = new DataGridViewTextBoxColumn();
header.HeaderText = "行/列";
header.Width = this.dgv_data.Width / (ColumnCount + 1);
header.DataPropertyName = "RowIndex";
header.SortMode = DataGridViewColumnSortMode.NotSortable;
this.dgv_data.Columns.Add(header);
//再添加其他列
for (int i = 1; i <= ColumnCount; i++)
{
DataGridViewImageColumn image = new DataGridViewImageColumn();
image.HeaderText = i.ToString();
image.Width = (this.dgv_data.Width - this.dgv_data.Columns[0].Width) / ColumnCount;
image.DataPropertyName = "Column" + i.ToString().PadLeft(2, '0');
image.SortMode = DataGridViewColumnSortMode.NotSortable;
image.AutoSizeMode = i == ColumnCount ? DataGridViewAutoSizeColumnMode.Fill : DataGridViewAutoSizeColumnMode.NotSet;
this.dgv_data.Columns.Add(image);
}
this.dgv_data.CellFormatting += Dgv_data_CellFormatting;
//双击修改
this.dgv_data.CellDoubleClick += Dgv_data_CellDoubleClick;
//悬浮显示
this.dgv_data.CellMouseEnter += Dgv_data_CellMouseEnter;
}
第四步:
这里表格需要做数据类型转换
private void Dgv_data_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex >= 1)
{
if (e.Value.ToString() == "1")
{
e.Value = Properties.Resources.red;
}
else
{
e.Value = Properties.Resources.green;
}
}
}
}