Boz
Boz

Reputation: 51

DataTable/DataGridView Row Number Display

I want to display in my first Column of my DataGridView but not found I a good solution. I try add a new Column to DGV but it crashed..

List<string[]> rows =  File.ReadAllLines(Open_CSV.FileName, 
                       Encoding.ASCII).Select(x => x.Split(';')).ToList();

DataTable dt = new DataTable();
foreach (string s in rows[0])
{
    dt.Columns.Add(s);
}
rows.RemoveAt(0);
rows.ForEach(x =>
{
    dt.Rows.Add(x);
});

DGV_DATA.DataSource = dt;

Do you have some solution where is the best place add in DataTable or DataGridView?

Upvotes: 0

Views: 1682

Answers (2)

Patrik
Patrik

Reputation: 1372

When using a DataSource, manually adding data might cause problems, as you experienced. Adding a row-number to the DataSource is obviously not a good idea, as long as the number does not belong to the data. In this case, one idea would be to display the number in the row-header, as described here.

In your case, where you building the DataSource by yourself, you might think of leaving the path of using the DataSource-Property and start adding the rows directly. The Rows-Property of the DataGridView can be used to add rows by hand. You only would need to build something like a List of DataGridViewRow-objects, which you can pass to the AddRange-method. To these DataGridViewRows you could add the additional column. And be sure to add that additional column also to the Columns-Collection of the DataGridView.

Upvotes: 2

Steve
Steve

Reputation: 216293

Not sure if it is very efficient but this could do the trick

List<string[]> rows =  File.ReadAllLines(......)
                         .Select((x,i) => 
                         string.Join(";", (i+1).ToString(), x)
                         .Split(';')).ToList();

You could use the version of Select that use the indexer of the current item in the sequence and add that index to the string that will be splitted.
My concerns are relative to the fact that in this way you build an additional string but, you don't need to change anything in the following code.

Upvotes: 1

Related Questions