如何在Winform DataGridView C#中创建不同的单元格格式? [英] How can I create different cell formats in Winform DataGridView C#

查看:273
本文介绍了如何在Winform DataGridView C#中创建不同的单元格格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataGridView,我绑定到一个DataTable。 DataTable是一个全数字值。要求DataGridView中的每n行都有文本,而不是数字值(为了用户可视地分隔各个部分)。我很高兴将此文本数据放入DataTable或DataGridView中,但是我无法看到一种方式将这个文本数据放在两个需要数字数据的列格式中 - 我得到一个不能把一个十进制的字符串两个都错误。任何想法如何在DataTable或DataGridView中更改特定行或单元格的格式?

解决方案

您可以提供一个处理程序对于DataGridView的CellFormatting事件,例如:

  public partial class Form1:Form 
{
DataGridViewCellStyle _myStyle = new DataGridViewCellStyle();

public Form1()
{
InitializeComponent();

_myStyle.BackColor = Color.Pink;
//我们还可以在这里提供一个自定义的格式字符串
//与_myStyle.Format属性
}

private void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
//每五行我想要我的自定义格式
//默认
if(e.RowIndex%5 == 0)
{
e.CellStyle = _myStyle;
e.FormattingApplied = true;
}
}

...

有关创建自己的样式的帮助,请参阅联机帮助中的 DataGridView.CellFormatting事件主题。


I have a DataGridView that I'm binding to a DataTable. The DataTable is a all numeric values. There is a requirement that every n rows in the DataGridView has text in it, rather than the numeric values (to visually separate sections for the user). I am happy to put this text data in the DataTable or in the DataGridView after binding, but I can't see a way to put this text data in either as the column formats for both require numeric data - I get a "can't put a string in a decimal" error for both. Any ideas how I change the format of a particular row or cell in either the DataTable or DataGridView?

解决方案

You can provide a handler for the DataGridView's CellFormatting event, such as:

    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;
            }
        }

        ...

For assistance on creating your own styles, refer to the DataGridView.CellFormatting Event topic in the online help.

这篇关于如何在Winform DataGridView C#中创建不同的单元格格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆