在运行时更改gridview中单元格的值 [英] changing the value of a cell in gridview at runtime

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

问题描述

我有一个处理数据库数据的 datagridview 。例如,我有一个有数字值的列,每个数字都表示一个字符串值。

  0 => 组1,
1 => group 2
等等...

用户必须将此数据视为可读格式,即0 =>组1。像这样:

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

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



简而言之:


  • 我希望在GridView中显示这些数据,而不会在我的数据库中做任何更改。
  • 我需要提议的格式。是否有一种简单的方法来制作该格式,即 n => group m

  • cellformatting不是我想要的。 CellFormatting只是根据数据格式对单元格进行格式化。 ( msdn



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

我希望能说出我的意思。



在此先感谢。

解决方案

让我们看看你得到了什么。


我想在GridView中显示这些数据, db。


太棒了,应该是这样的。 数据必须与数据表示分开。


cellformatting不是我我想在这里。 cellformatting只是根据数据格式来格式化单元。


错!

格式正是您所需要的。一个相同的数据可以用多种方式表示。例如,可以使用数千种方式(格式)显示(格式化)一个数字或日期值。这正是 string.Format (和其他格式)方法。另一个例子是复选框,显示 bool 值。又一个例子是 ComboBox 显示 ValueMember DisplayMember 。等等。实际上,您的需求是 Format 函数的变体,可以通过自定义数字格式字符串。您只需要设置 DataGridViewColumn.DefaultCellStyle 属性格式为Group 0。



如果格式不够,与某些人所说的相反, CellFormatting 事件正是你所需要的。


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

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


大多数情况下性能可以忽略不计,因为只有在需要在屏幕上显示时才将值转换为字符串,并且与行总数相比,屏幕可以有限的行数(如果您有大量数据) 。/ b>

值/显示文本分隔的优点之一是网格排序能够正常工作(通过数字而不是文本)。

总之,不要被愚弄来转换您的数据存储值以供显示。每个控件都有格式化功能,只需使用它们即可。既然你问了一个简单的方法,格式属性是最简单但有效的解决方案。



这里是一个使用两种格式化方法的100,000行示例(评论一个并取消其他人的评论)。您可以看到绝对没有性能问题,并且 GroupId 列排序可以正常工作。

 使用系统; 
使用System.Data;
使用System.Linq;
使用System.Windows.Forms;

命名空间示例
{
静态类程序
{
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;
}
}
};

$ b [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);
}
}
}


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...

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"

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.

so in brief:

  • 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)

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

I hope to say what I mean.

thanks in advance.

解决方案

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 is not what I'm wanting here. cellformatting just formats the cell in terms of the data format.

Wrong!

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.

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.

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.

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).

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.

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天全站免登陆