Tutorial :DataGridView: Format values without actually changing the bounded data?



Question:

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

I have a DataGridView with a BindingSource 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


Solution:1

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;      }  }  


Solution:2

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »