如何在运行时更改gridview中单元格的值? [英] How to change the value of a cell in a gridview at runtime?

查看:294
本文介绍了如何在运行时更改gridview中单元格的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datagridview,它可以处理数据库中的数据.我有一列具有数字值,并且每个数字都是字符串值的表示形式,例如,

I have a datagridview that manipulate data from a DataBase. I have a column that has numeric value and each number is representation of a string value, for example,

0 => "group 1", 
1 => "group 2" 
and so on...

用户必须将此数据视为可读格式,表示0 => 组1".像这样的东西:

User must see this data as an readable format, meaning 0 => "group 1". something like this:

id          priceGroupID
----------- ------------
1234        -1 => "group -1"
36968       0  => "group  0"
1           2  => "group  2"
2           2  => "group  2"
3           2  => "group  2"
1003        2  => "group  2"

在此链接中:( stackoverflow.com/questions/10314996/…)代表一个想法,但我还需要其他东西.更强大的功能.不要害羞,如果没有其他方法,请告诉我没有.

in this link: (stackoverflow.com/questions/10314996/…) represent an idea, but I want something else. something more powerful. don't be shy, if there is no other way please tell me that there is not.

所以简单点:

  • 我想在Gridview中显示此数据,而无需对数据库进行任何更改.
  • 我想要建议的格式.有没有一种简单的方法可以制作这种格式,即n => "group m".
  • 单元格格式化不是我想要的. CellFormatting只是根据数据格式对单元格进行格式化. ( msdn )
  • I want to display this data in the Gridview without any change in my db.
  • I want the proposed format. Is there a simple way to make that format, meaning n => "group m".
  • cellformatting is not what I'm wanting here. CellFormatting just formats the cell in terms of the data format. (msdn)

还有一件事:我的编程语言是Windows应用程序中的c#.

and one more thing: my programming language is c# in the windows app.

我希望说出我的意思.

提前谢谢.

推荐答案

让我们看看您得到了什么.

Let see what you got.

我想在网格视图中显示此数据,而无需更改数据库.

I want to display this data in the gridview without change in my db.

太好了,这就是应该的样子. 数据必须与数据表示形式分开.

Great, this is how it should be. Data must be separated from the data representation.

单元格格式化不是我想要的. cellformatting只是根据数据格式对单元格进行格式化.

cellformatting is not what I'm wanting here. cellformatting just formats the cell in terms of the data format.

错了!

格式化正是您所需要的.相同的数据可以用多种方式表示.例如,可以使用数千种方式(格式)来显示(格式化)一个或一个数字或日期值.这正是 string.Format的内容(和其他Format)方法可以.另一个示例是显示bool值的Checkbox.另一个示例是ComboBoxValueMember显示为DisplayMember.等等.

Formatting is exactly what you need. One and the same data can be represented in many ways. For instance, one and the number or date value can be shown (formatted) using thousands ways (formats). This is exactly what string.Format (and other Format) methods do. Another example is Checkbox showing bool value. Yet another example is ComboBox displaying ValueMember as DisplayMember. Etc.

实际上,您的要求是Format函数的变体,可以使用

In fact your requirement is a variation of the Format function and can be achieved with a Custom Numeric Format String. All you need is to set DataGridViewColumn.DefaultCellStyle property Format to "Group 0".

如果格式不够用,这与某些人所说的相反,则

If the format wasn't enough, contrary to what some people say, the CellFormatting event is exactly what you need.

默认情况下,DataGridView控件将尝试将单元格的值转换为适合显示的格式.例如,它将把数字值转换为字符串,以显示在文本框单元格中.您可以通过设置由诸如DefaultCellStyle属性之类的属性返回的DataGridViewCellStyle的Format属性来指示要使用的格式约定.

By default, the DataGridView control will attempt to convert a cell's value into a format suitable for display. For example, it will convert a numerical value into a string for display in a text box cell. You can indicate the formatting convention to use by setting the Format property of the DataGridViewCellStyle returned by properties such as the DefaultCellStyle property.

如果标准格式不足,则可以通过处理CellFormatting事件自定义格式.通过此事件,您可以指示确切的显示值以及用于单元格显示的单元格样式,例如背景和前景色.这意味着您可以针对任何类型的单元格格式处理此事件,而不管单元格值本身是否需要格式化.

If the standard formatting is insufficient, you can customize the formatting by handling the CellFormattingevent. This event lets you indicate the exact display value as well as the cell styles, such as background and foreground color, to use for the cell display. This means you can handle this event for any kind of cell formatting, regardless of whether the cell value itself needs formatting.

在大多数情况下,对性能的影响可以忽略不计,因为仅在需要在屏幕上显示该值时,该值才会转换为字符串,并且与行总数相比,屏幕可以限制行数(以防万一)您拥有大量数据).

The effect on the performance is negligible most of the time because the value is converted to string only when needed to be displayed on the screen, and the screen can a limited number of rows compared to the total number of rows (in case you have a huge data).

值/显示文本分离的优点之一是,网格排序可以正确地进行排序(按数字而不是按文本).

One of the advantages of the value/display text separation is that the grid sorting works correctly (by numeric rather than by text).

最后,不要愚弄转换您的数据存储值以进行显示.每个控件都具有格式化功能,只需使用它们即可.由于您要求一种简单的方法,因此Format属性是您所用的最简单但有效的解决方案.

To conclude, don't be fooled to convert your data storage values for display. Every control has formatting capabilities, just use them. Since you asked for a simple way, Format property is the simplest yet effective solution in your case.

以下是使用两种格式化方法的行数为100,000的示例(注释一个,取消注释另一个).您可以看到绝对没有性能问题,并且GroupId列排序可以正常工作.

Here is an example with 100,000 rows using both formatting approaches (comment the one and uncomment the other to play with). You can see that there is absolutely no performance issues, and GroupId column sorting works correctly.

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

namespace Samples
{
    static class Program
    {
        static void UseFormat(DataGridView dg)
        {
            dg.ColumnAdded += (sender, e) =>
            {
                if (e.Column.DataPropertyName == "GroupId")
                {
                    e.Column.DefaultCellStyle.Format = "Group 0";
                }
            };
        }

        static void UseCellFormatting(DataGridView dg)
        {
            dg.CellFormatting += (sender, e) =>
            {
                if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
                {
                    var column = dg.Columns[e.ColumnIndex];
                    if (column.DataPropertyName == "GroupId" && e.Value != null)
                    {
                        e.Value = "Group " + e.Value.ToString();
                        e.FormattingApplied = true;
                    }
                }
            };
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form();
            var dg = new DataGridView { Dock = DockStyle.Fill, Parent = form, ReadOnly = true, AllowUserToAddRows = false };
            UseFormat(dg);
            //UseCellFormatting(dg);
            var data = new DataTable();
            data.Columns.Add("Id", typeof(int));
            data.Columns.Add("GroupId", typeof(int));
            var groupIds = Enumerable.Range(0, 15).ToArray();
            for (int i = 0; i < 100000; i++)
                data.Rows.Add(i, groupIds[i % groupIds.Length]);
            dg.DataSource = data;
            Application.Run(form);
        }
    }
}

这篇关于如何在运行时更改gridview中单元格的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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