开发者

DataGridView: Format values without actually changing the bounded data?

I've been searching through the web but I have not been able to find an answer.

I have a DataGridView with a Bin开发者_开发技巧dingSource bounded, which has a List of objects of a custom class. Among the fields of the class, I have a string field which I want to show using

Path.GetFileName();

because it contains the whole filepath and what I want is to show just the name of the file but keeping the filepath (i.e., the bounded data intact) in the bounded object.

It is there any way to do this (Format, template, styles, ...)? because anytime I change the Value field of the Cell, it changes the value of the object (which it's logic).

Many thanks in advance


Use the DataGridView.CellFormatting event on the DataGridView. This will give you a DataGridViewCellFormattingEventArgs object with information about the current cell, including the row and column and the unformatted value. You update the Value property to the formatted value and set FormattingApplied to true, and the DataGridView will render that value.

Something like this:

private void dataGridView1_CellFormatting(object sender, 
    DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0) // Check for the column you want
    {
        e.Value = Path.GetFileName(e.Value.ToString());
        e.FormattingApplied = true;
    }
}


The Binding class has a Format() and Parse() event handler where you can define how the data will be formatted in both ways.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜