合并Datagridview上多行列上的值

如何解决合并Datagridview上多行列上的值

我有Visual Studio2019。该项目是.Net Framework 4.8上基于C#的.Net Windows窗体。

我有一个Datagridview,它显示了来自不同数据库(MS SQL和Postgresql)的一些表数据。

我合并了这些数据库,结果太长,因此我们无法在屏幕上显示它;但我们必须在该屏幕上查看40列以上的所有可用数据。减小字体大小是不合理的。

因此,提出的解决方案是以这种方式将一些值合并在同一列上(请参见本示例):

实际数据视图:

actual

查看方式:

goal

如果您有任何想法,或者您知道Datagridview的替代方案,请分享。

谢谢。

解决方法

您可以自定义datagridview的行和列,以在datagridview上获得多行列。

我认为数据表是数据库中的表。

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;

private void Form1_Load(object sender,EventArgs e)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name");
            table.Columns.Add("Field1");
            table.Columns.Add("Field2");
            table.Columns.Add("Field3");
            table.Columns.Add("Field4");
            table.Columns.Add("Field5");
            table.Columns.Add("Field6");
            table.Columns.Add("Field7");
            table.Rows.Add("test1",1,2,3,4,5,6,7);
            table.Rows.Add("test2",7);
            table.Rows.Add("test3",7);
            dataGridView1.ColumnHeadersVisible = false;
            for (int i = 0; i < table.Columns.Count/2; i++)
            {
                dataGridView1.Columns.Add("","");
            }
            string[] columnNames = table.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray();
            int count = table.Columns.Count/2;
            var col1 = columnNames.Take(count).ToArray();
            var col2= columnNames.Skip(count).Take(count).ToArray();
            dataGridView1.Rows.Add(col1);
            dataGridView1.Rows.Add(col2);
            object[] arr;
            for (int i = 0; i < table.Rows.Count; i++)
            {
                arr = table.Rows[i].ItemArray;
                var row1=arr.Take(count).ToArray();
                var row2 = arr.Skip(count).Take(count).ToArray();
                dataGridView1.Rows.Add(row1);
                dataGridView1.Rows.Add(row2);

            }
           
        }

结果:

enter image description here

,

在审查了您的问题之后,我不得不说恕我直言,您的解决方案没有给最终用户太多考虑,或者代码是否必须获取其中一个值。将字段堆叠到单个列中会“引起”两个问题,恕我直言……如上所述,一个问题是用户将不得不做额外的工作,并检查标题的顺序以区分哪个字段值是哪个……一个微妙的问题(讨厌)非直观的额外步骤。第二,如果允许用户更改字段或代码需要对字段进行分级,那么将需要进行额外的工作来区分哪个字段使用哪个值。对于用户来说,额外的工作以及对编码人员来说,额外的工作听起来并不是一个好的开始。

对不起,我的咆哮。幸运的是,如果您要按照问题所示获取一张表,然后将其转换为您所描述的表,那么下面的代码应该可以做到这一点。它基本上会创建“两”(2)个字段列。这样每一列都包含两个字段。代码很hacky,但我希望它不太复杂。我在代码中做了很多注释。需要注意的是,由于我们为每列添加两个字段,并且(据我所知)DataGridView不允许使用双列标题,因此代码不使用列标题行,而是使用两个列标题的网格的前两行。如果需要,这将使您可以格式化两行,使其看起来像标题和/或颜色代码。

最后,恕我直言,这是一个更好的解决方案。如前所述,数据透视将起作用,但是鉴于数据如何存储在原始表中,存在一些问题。在我们切换行和列的基本枢纽中,发布的示例将具有三(3)列…“ Jim”,“ Hugh”和“ Terrance”。那么行数将是(一(1)+但是许多字段/字段列)。额外的“一个”是字段“姓氏”。鉴于此,它可能看起来像……

                   Jim       Hugh         Terrance
LastName           Carey     Jackman      Hill
Field1             1         a            N/A
Field2             2         b            N/A
      ……..

很明显,“ LastName”应与列标题一起使用。因此,转置/透视可能看起来像……

                   Jim Carey      Hugh Jackman      Terrance Hill
Field1             1              a                 N/A
Field2             2              b                 N/A
      ……..

恕我直言,这对于用户标识字段将更加直观,并且如果我们需要引用特定值,则不应进行任何额外的编码。下图显示了以下代码的完整示例。将三(3)DataGridViews放到表单上并粘贴我的代码。左上方的网格是原始数据。左下方的网格是根据您的要求进行的转置,最后,右侧的网格是考虑到您的困境后我认为最有效的网格。

enter image description here

关于右边最后一个网格的注释……最初,就像您解决方案中的列标题行一样,我将字段作为网格中的一列。如果需要,更改代码并不难。但是,该代码当前将字段名称添加为网格中的“行标题”。由于DataTable确实没有行标题,因此必须在设置数据源之后“ Load”事件进行添加。同样,将字段移到DataTable中添加的列将不难。

为使本示例更完整,下面是创建一些测试数据的代码。传入参数totalCols将使totalCols中的DataTable列成为“字段”值。

private DataTable GetDataFromDB(int totalCols) {
  DataTable dt = new DataTable();
  dt.Columns.Add("Name",typeof(string));
  dt.Columns.Add("LastName",typeof(string));
  for (int i = 1; i <= totalCols; i++) {
    dt.Columns.Add("Field" + i,typeof(string));
  }
  DataRow curRow;
  string name;
  string lName;
  for (int i = 1; i < 4; i++) {
    switch (i) {
      case 1:
        name = "Jim";
        lName = "Carrey";
        break;
      case 2:
        name = "Hugh";
        lName = "Jackman";
        break;
      default:
        name = "Terence";
        lName = "Hill";
        break;
    }
    curRow = dt.NewRow();
    curRow["Name"] = name;
    curRow["LastName"] = lName;
    if (i < 3) {
      for (int j = 2; j < dt.Columns.Count; j++) {
        curRow[j] = "N" + i + "F" + (j - 1);
      }
    }
    dt.Rows.Add(curRow);
  }
  return dt;
}

我们将使用三(3)个全局DataTables,每个网格一个。

DataTable originalDT;
DataTable pivotDT1;
DataTable pivotDT2;

将每个网格设置为正确的DataTable并为每个网格设置某些特定格式的加载事件。

private void Form1_Load(object sender,EventArgs e) {
  originalDT = GetDataFromDB(45);
  dataGridView1.DataSource = originalDT;
  // pivot 1 - bottom left grid
  pivotDT1 = PivotTable(originalDT);
  dataGridView2.DataSource = pivotDT1;
  dataGridView2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  dataGridView2.Rows[0].DefaultCellStyle.BackColor = Color.Blue;
  dataGridView2.Rows[1].DefaultCellStyle.BackColor = Color.Blue;
  dataGridView2.Rows[0].DefaultCellStyle.ForeColor = Color.White;
  dataGridView2.Rows[1].DefaultCellStyle.ForeColor = Color.White;
  dataGridView2.Columns[0].Frozen = true;
  // pivot 2 - right grid
  pivotDT2 = PivotTable2(originalDT);
  dataGridView3.DataSource = pivotDT2;
  int dgvRow = 0;
  // add column headers as row headers in the grid
  for (int i = 2; i < originalDT.Columns.Count; i++) {
    dataGridView3.Rows[dgvRow++].HeaderCell.Value = originalDT.Columns[i].ColumnName;
  }
  dataGridView3.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
}

最后,这两种数据透视/转换方法……

使用您的解决方案并显示在左下方的网格中……

private DataTable PivotTable(DataTable originalDT) {
  DataTable pivotDT = new DataTable();
  // the number of columns will be half the original number of columns
  int halfCols = Math.DivRem(originalDT.Columns.Count,out int rem);
  // if there is a remainder then there is an odd number of columns and we need to add 1 col
  if (rem > 0) {
    halfCols++;
  }
  // add the columns to the pivot table
  for (int i = 0; i < halfCols; i++) {
    pivotDT.Columns.Add();
  }
  // the number of rows will be the number of original rows times 2
  // PLUS 2 additional rows for the headers
  for (int i = 0; i < (originalDT.Rows.Count * 2) + 2; i++) {
    pivotDT.Rows.Add();
  }
  // Add the two header rows from the column names
  int originalCol = 0;
  for (int i = 0; i < halfCols; i++) {
    pivotDT.Rows[0][i] = originalDT.Columns[originalCol++].ColumnName;
    // if the original table had an odd number of columns
    // then the last column only had one field 
    // - there would never be a column without at least one field
    if (originalCol < originalDT.Columns.Count) {
      pivotDT.Rows[1][i] = originalDT.Columns[originalCol++].ColumnName;
    }
  }
  // finally add the rows from the original table.
  int pivotRow = 2;
  int pivotCol = 0;
  int curPivotRow;
  int curPivotCol;
  string value;
  for (int originalRow = 0; originalRow < originalDT.Rows.Count; originalRow++) {
    curPivotRow = pivotRow;
    curPivotCol = pivotCol;
    for (originalCol = 0; originalCol < originalDT.Columns.Count; originalCol++) {
      value = originalDT.Rows[originalRow][originalCol].ToString();
      if (string.IsNullOrEmpty(value)) {
        value = "N/A";
      }
      pivotDT.Rows[curPivotRow][curPivotCol] = value;
      // if this is the first item then simply bump the pivot row
      if (curPivotRow < pivotRow + 1) {
        curPivotRow++;
      }
      else { // this is the second item -
             // we want the curpivot row to start back at the starting pivotRow
             // then move over a column for the next two columns in the original table
        curPivotRow = pivotRow;
        curPivotCol++;
      }
    }
    // new row in the original data start back at column 0 in the pivot table
    // and bump the row index by two since we added two rows
    pivotRow += 2;
    pivotCol = 0;
  }
  return pivotDT;
}

我的解决方案显示在右边的网格中。

private DataTable PivotTable2(DataTable originalDT) {
  DataTable pivotDT = new DataTable();
  for (int i = 0; i < originalDT.Rows.Count; i++) {
    pivotDT.Columns.Add();
  }
  for (int i = 0; i < originalDT.Columns.Count - 2; i++) {
    pivotDT.Rows.Add();
  }
  int pivotCol = 0;
  foreach (DataRow row in originalDT.Rows) {
    pivotDT.Columns[pivotCol++].ColumnName = row[0].ToString() + " " + row[1].ToString();
  }
  int pivotRow = 0;
  pivotCol = 0;
  string value;
  for (int i = 0; i < originalDT.Rows.Count; i++) {
    for (int j = 2; j < originalDT.Columns.Count; j++) {
      value = originalDT.Rows[i][j].ToString();
      if (string.IsNullOrEmpty(value)) {
        value = "N/A";
      }
      pivotDT.Rows[pivotRow++][pivotCol] = value;
    }
    pivotCol++;
    pivotRow = 0;
  }
  return pivotDT;
}

最后,我不太熟练使用SQL,但是,我敢保证可以创建一个SQL过程,该过程将直接从数据库中产生我的解决方案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-