• C#实现DataGridView控件行列互换的方法
  • 2018年03月08日
  • 网络收集

本文实例讲述了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#程序设计有所帮助。