问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/10314996/changing-values-in-datagridview-depending-on-existing-values