views:

938

answers:

2

i have a column item-code, inside my database which i have bound to a datagrid view. The item-code comes in this format "A-B-C", i wish only to show the "B" part of the code, i have bound this column to the gridview and now wish to make it show the substring. I tried defaultcellstyle.format but don't know how to get a substring for it.

+2  A: 

Is it a possibility to add a new property to your bound object, something like ItemCodePart, which returns the middle part of your item-code, then bind this property to the column instead of item-code? That would be the simplest way.

Another option is to handle the CellFormatting event of the DataGridView and set e.Value to the part of item-code you want to show:

Private Sub myDataGridView_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles myDataGridView.CellFormatting

If e.ColumnIndex = MyItemPartColumn.Index Then
    Dim currentValue As String = CStr(myDataGridView.Item(e.ColumnIndex, e.RowIndex).Value)
    Dim parts As String() = currentValue.Split(New Char() {"-"c})
    e.Value = parts(1)
End If

End Sub
Meta-Knight
the object is a datatable, can you tell me how i can add property to it?
Anirudh Goel
DataColumn is the class for a column and you add via the datatable.columns.add method.Then on your rows you would access the new column as normal and set it's value to the formatted version of your item.
klabranche
With a datatable maybe the second option is simpler ;-)
Meta-Knight
Added complete code, didn't test it though.
Meta-Knight
i appreciate the code, nice work.
Anirudh Goel
A: 

RowDataBound event - You can edit the text of that field.

klabranche