根据现有值更改dataGridView中的值 [英] Changing values in dataGridView depending on existing values
问题描述
谢谢
通常的方法是使用 CellGormatting
事件的 DataGridView
。
这是一个简单的例子:
dataGridView1 .CellFormatting + = new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
void dataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{
if(e.Value == null)
return;
string stringValue =(string)e.Value;
stringValue = stringValue.ToLower();
if(e.Value ==1)
{
e.Value =string for one;
e.FormattingApplied = true;
}
}
eventargs有一个ColumnIndex属性,可用于请确保您只格式化正确的列。
需要注意的是,每当单元格绘制时,这个单元格格式化事件将被引发,因此您不应该在事件中做很多工作处理程序。例如,对于您的值的数据库查找将是一个很大的错误!
单元格格式化事件不会影响底层数据,因此您仍然会在数据源中使用整数。
有关此事件的更多信息,请访问MSDN 这里。
I'm remaking an application that my client owns (meaning that I did not create the original application), and one of requests is to simplify the data displayed in one of dataGridViews (the data is drawn from an existing database). The problem is that in the data table that this display uses, one of columns represents a type of usage of a certain product and is represented by an ordinary number. So far my client had to read from another document what does a specific number mean. Now he wants me to replace the numbers with descriptive strings (he sent me a list describing which number refers to which description), but I am not allowed to alter the database. How can I change the content of that column (in my dataGridView only, not in the database) to show the text instead of numbers?
Thanks
The usual way to do this is by using the CellFormatting
event of the DataGridView
.
Here is a simple example:
dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.Value == null)
return;
string stringValue = (string)e.Value;
stringValue = stringValue.ToLower();
if (e.Value == "1")
{
e.Value = "string for one";
e.FormattingApplied = true;
}
}
The eventargs have a ColumnIndex property that you can use to ensure that you only format the correct column.
One this to note is that this cell formatting event is raised whenever the cell paints so you should not do heavy work in the event handler. For example a db lookup for your values would be a big mistake! Instead store this in an in memory dictionary.
The cell formatting event does not affect the underlying data so you will still have the integers in your data source.
Some more info on this event is on MSDN here.
这篇关于根据现有值更改dataGridView中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!