How to ignore underscores in header when displaying .net DataTable that was populated with KBCsv?

May 2, 2013 at 5:47 PM
Edited May 2, 2013 at 5:49 PM
I have a csv file with header and I am using KBCsv to populate the DataTable. The header text contains underscores and when displaying the DataTable the first underscore (is missing) is used as ALT shortcut in the UI.
DataTable dataTable = new DataTable();

using (var reader = new CsvReader(FileNameTextBox.Text))
{
       //How to escape the first underscore or disable the ALT shortcut
       reader.ReadHeaderRecord();       
       dataTable.Fill(reader);
}
How to escape the first underscore without affecting the actual header names? or to display the header names as it is without the ALT shortcut. Any ideas or suggestions are greatly appreciated.

Ash
Coordinator
May 2, 2013 at 6:58 PM
Hi Ash,

I'm not sure I follow completely. Can you please provide an example of the CSV you're parsing?

Thanks
May 2, 2013 at 7:38 PM
I have a csv file with header line and data, I used KBCsv to fill the DataTable easily, and then used the datatable.AsDataView() as the source for DataGrid. When the dataGrid is displayed, the column header doesn't display the first underscore.
"date_recorded","date_recorded_last"
Image

So, my recent attempt to see if there was a way to replace the first underscore with two underscores in the HeaderRecord.
string doubleUnderscore = "__";
var rgx = new Regex("_");
HeaderRecord newHeader = new HeaderRecord(reader.HeaderRecord.Select(s => rgx.Replace(s, doubleUnderscore, 1)));
reader.HeaderRecord = newHeader; 
But I get this error"The CsvReader has already passed the first record, so this operation is not permitted."

Ashley
Coordinator
May 3, 2013 at 12:00 PM
Thanks - I understand now.

I think you're trying to change things at the wrong level. Ideally your data should remain agnostic of the view. Really you're running into a limitation of binding directly to your data instead of placing a view model in between the data and view. Such a view model could provide insulation between your data and view, maintaining the integrity of both.

However, if you're intent on using the data directly, you could do something like this:
HeaderRecord headerRecord = null;
DataTable dataTable = new DataTable();

using (var reader = new CsvReader(FileNameTextBox.Text))
{
    headerRecord = reader.ReadHeaderRecord();
}

using (var reader = new CsvReader(FileNameTextBox.Text))
{
    reader.HeaderRecord = new HeaderRecord(headerRecord.Select(x => x.Replace("_", "__")));
    reader.SkipRecord();

    dataTable.Fill(reader);
}
HTH,
Kent
May 3, 2013 at 12:19 PM

Thanks, exactly what I was looking for. Will give it a try.
Ash