【问题标题】:merging two datagridview columns into one new column将两个 datagridview 列合并为一个新列
【发布时间】:2020-12-25 07:28:53
【问题描述】:

我想将两个 datagridview 列合并为一个新列。

我首先将两个 col 的 Visible 属性更改为 false,然后我尝试添加新的 col,该值必须格式化为 col1Value 和 col2Value 是上述列的值:

string.Format("{0} per {1}", col1Value, col2Value);

我的代码

reportResultForm.dgvResult.Columns["Height"].Visible = false;
reportResultForm.dgvResult.Columns["Width"].Visible = false;
DataGridViewColumn col = new DataGridViewColumn();
col.DefaultCellStyle.Format = "{0} per {1}";
col.CellTemplate = new DataGridViewTextBoxCell();
dgvResult.Columns.Add(col);

但我不知道该怎么做!请帮我。我的方法是真的吗?

【问题讨论】:

  • 您希望如何将两列合并为一列?数据不同,那么你将如何处理不同的数据?
  • 我想使用 col1 和 col2 的值来以顶级格式显示 newcol。 newcolValue = string.Format("{0} per {1}", col1Value, col2Value)

标签: c# winforms datagridview


【解决方案1】:

您可以自己实现 DataGridViewTextBoxCell 并为其重写 GetFormattedValue 方法。在那里,您可以为您的列返回格式化值,下面是一个示例:

// use custom DataGridViewTextBoxCell as columns's template
col.CellTemplate = new MyDataGridViewTextBoxCell();

...

// custom DataGridViewTextBoxCell implementation 
public class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    protected override Object GetFormattedValue(Object value,
        int rowIndex,
        ref DataGridViewCellStyle cellStyle,
        TypeConverter valueTypeConverter,
        TypeConverter formattedValueTypeConverter,
        DataGridViewDataErrorContexts context)
    {
        return String.Format("{0} per {1}",
            this.DataGridView.Rows[rowIndex].Cells[0].Value,
            this.DataGridView.Rows[rowIndex].Cells[1].Value);
    }
}

希望这会有所帮助,问候

【讨论】:

    【解决方案2】:

    试试这个(它对我有用):

    reportResultForm.dgvResult.Columns.Add("newColumn", "New Column");
            foreach (DataGridViewRow row in reportResultForm.dgvResult.Rows)
            {
                string height= row.Cells["Height"].Value.ToString();
                string width= row.Cells["Width"].Value.ToString();
                string formattedCol= string.Format("{0} per {1}", height, width);
                row.Cells["newColumn"].Value = formattedCol;
            }
    

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 2014-04-01
      • 2015-04-01
      • 2014-01-03
      • 2021-04-04
      • 2013-01-23
      • 2010-10-26
      相关资源
      最近更新 更多