【问题标题】:How can I create different cell formats in Winform DataGridView如何在 Winform DataGridView 中创建不同的单元格格式
【发布时间】:2009-02-26 22:30:45
【问题描述】:

我有一个绑定到 DataTable 的 DataGridView。
DataTable 是一个全数字值。
要求 DataGridView 中的每 n 行都包含文本,而不是数值(以便在视觉上为用户分隔部分)。

我很高兴在绑定后将此文本数据放入 DataTable 或 DataGridView 中,但我看不到将这些文本数据放入其中的任何一种方法,因为两者的列格式都需要数字数据 - 我得到一个“两者都无法将字符串放入十进制”错误。

知道如何更改 DataTable 或 DataGridView 中特定行或单元格的格式吗?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    您可以为DataGridView的CellFormatting事件提供处理程序,例如:

    public partial class Form1 : Form
    {
        DataGridViewCellStyle _myStyle = new DataGridViewCellStyle();
    
        public Form1()
        {
            InitializeComponent();
    
            _myStyle.BackColor = Color.Pink;
            // We could also provide a custom format string here 
            // with the _myStyle.Format property
        }
    
        private void dataGridView1_CellFormatting(object sender, 
            DataGridViewCellFormattingEventArgs e)
        {
            // Every five rows I want my custom format instead of the default
            if (e.RowIndex % 5 == 0)
            {
                e.CellStyle = _myStyle;
                e.FormattingApplied = true;
            }
        }
    
        //...
    }
    

    有关创建自己的样式的帮助,请参阅在线帮助中的DataGridView.CellFormatting Event 主题。

    【讨论】:

      【解决方案2】:

      这能解决您的问题吗?

      // Set the data source.
      dataGridView1.DataSource = dataTable1;
      
      // Create a new text box column.
      DataGridViewColumn c1 = new DataGridViewTextBoxColumn();
      const string C1_COL_NAME = "Custom1";
      c1.Name = C1_COL_NAME;
      
      // Insert the new column where needed.
      dataGridView1.Columns.Insert(1, c1);
      
      // Text can then be placed in the rows of the new column.
      dataGridView1.Rows[0].Cells[C1_COL_NAME].Value = "Some text...";
      

      原始数据表绑定应该仍然存在。

      【讨论】:

        【解决方案3】:

        我已将Janus GridEx 用于此类非标准行为。 (部分是因为它的功能远不止这些,比如分组和求和、卡片视图等。)网站上有一些很好的演示。

        (不是推销;我只是在使用他们的组件时获得了很好的体验。)


        (来源:janusys.com

        【讨论】:

        • 所以你认为我的要求不能用标准的DataGridView来满足?
        • 好吧,我不敢这么说,因为这里有人比我更有经验修改 WinForms 控件行为。坦率地说,我很惊讶没有其他人提出来。
        猜你喜欢
        • 1970-01-01
        • 2014-11-20
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多