C#实现DataGridView控件行列互换的方法
程序员文章站
2023-11-04 21:52:40
本文实例讲述了c#实现datagridview控件行列互换的方法。分享给大家供大家参考。具体如下:
该示例程序是一个windows窗体应用程序,有左右两个datagrid...
本文实例讲述了c#实现datagridview控件行列互换的方法。分享给大家供大家参考。具体如下:
该示例程序是一个windows窗体应用程序,有左右两个datagridview控件:dgvleft和dgvright
dgvright除时间外的每一行是dgvleft的一列
private void form1_load(object sender, eventargs e) { //c#中确定控件datagridview根据内容自动调整列宽长度的属性 //是autosizecolumnsmode,将它的值设置为allcells时可以达到该效果。 //调整行每行头部的宽度(可以更好地显示出数字) this.dgvleft.rowheaderswidth = 50; this.dgvright.rowheaderswidth = 50; //左侧数据表 datatable dtleft = new datatable(); dtleft.columns.add("c1"); dtleft.columns.add("c2"); dtleft.columns.add("c3"); dtleft.columns.add("time"); dtleft.rows.add("1-1", "1-2", "1-3", datetime.now.toshorttimestring()); dtleft.rows.add("2-1", "2-2", "2-3", datetime.now.toshorttimestring()); dtleft.rows.add("3-1", "3-2", "3-3", datetime.now.toshorttimestring()); dtleft.rows.add("4-1", "4-2", "4-3", datetime.now.toshorttimestring()); dtleft.rows.add("5-1", "5-2", "5-3", datetime.now.toshorttimestring()); dtleft.rows.add("6-1", "6-2", "6-3", datetime.now.toshorttimestring()); dgvleft.datasource = dtleft; //右侧数据表,是左侧数据表的转置 datatable dtright = new datatable(); for (int i = 0; i < dtleft.rows.count; i++) { dtright.columns.add("c" + i); } dtright.columns.add("time"); for (int i = 0; i < dtleft.columns.count - 1; i++) { object[] obj = new object[dtleft.rows.count + 1]; for (int j = 0; j < dtleft.rows.count; j++) { obj[j] = dtleft.rows[j][i]; } obj[obj.length - 1] = datetime.now.toshorttimestring(); dtright.rows.add(obj); } dgvright.datasource = dtright; }
每一行的行号可以通过下面的方法添加
//datagridview 控件 dgvleft 的 rowsadded 事件 private void dgvleft_rowsadded(object sender, datagridviewrowsaddedeventargs e) { for (int i = 0; i < dgvleft.rows.count; i++) { this.dgvleft.rows[i].headercell.style.alignment = datagridviewcontentalignment.middleright; this.dgvleft.rows[i].headercell.value = i.tostring(); } } //datagridview 控件 dgvleft 的 rowsremoved 事件 private void dgvleft_rowsremoved(object sender, datagridviewrowsremovedeventargs e) { for (int i = 0; i < dgvleft.rows.count; i++) { this.dgvleft.rows[i].headercell.style.alignment = datagridviewcontentalignment.middleright; this.dgvleft.rows[i].headercell.value = i.tostring(); } } //datagridview 控件 dgvright 的 rowsadded 事件 private void dgvright_rowsadded(object sender, datagridviewrowsaddedeventargs e) { for (int i = 0; i < dgvright.rows.count; i++) { this.dgvright.rows[i].headercell.style.alignment = datagridviewcontentalignment.middleright; this.dgvright.rows[i].headercell.value = i.tostring(); } } //datagridview 控件 dgvright 的 rowsremoved 事件 private void dgvright_rowsremoved(object sender, datagridviewrowsremovedeventargs e) { for (int i = 0; i < dgvright.rows.count; i++) { this.dgvright.rows[i].headercell.style.alignment = datagridviewcontentalignment.middleright; this.dgvright.rows[i].headercell.value = i.tostring(); } }
运行效果如下图所示:
希望本文所述对大家的c#程序设计有所帮助。
上一篇: C#实现求一组数据众数的方法
下一篇: C#不重复输出一个数组中所有元素的方法