开发者

Splitting value/data from one column into 3 separate column in c#.net

I have some confusion in reading/displaying csv file in datagridview.

Here is the situation, I am reading csv file which consist of 7 data/column/fields in a row. I am trying to display those data in datagridview which contain 9 column/fields.

Now, 7 data/column/field in csv file consist value either from 0 to 3 or in combination of 1 to 3. I wan开发者_如何学编程t to split the data of 7 column/field in csv into last 3 column/field of datagridview.

eg). 7 column in csv field consist 123 then in datagridview it value in column/field 7 = 1 column/field 8 = 2 and column/field 9 = 3.

I want to know that, is it possible to split value into 3 different column in C#.NET.

Thanks, Rushabh Shah.


I would create a class to store each record (row) in your CSV. In this class expose nine properties that correspond to the nine columns in your DataGridView. The class would handle the logic of splitting the values of your seventh column into the eight and nineth columns like you described.

When you read in your CSV create instances of this class, put them in a List (or another collection) and bind the list to the DataGridView.

Here's what I mean. Create the following class:

class Record
{
    public Record(string line) {
        string[] fields = line.Split(',');
        Field1 = fields[0];
        Field2 = fields[1];
        Field3 = fields[2];
        Field4 = fields[3];
        Field5 = fields[4];
        Field6 = fields[5];
        Field7 = fields[6].Substring(0, 1);
        Field8 = fields[6].Substring(1, 1);
        Field9 = fields[6].Substring(2, 1);
    }
    public string Field1 { get; private set; }
    public string Field2 { get; private set; }
    public string Field3 { get; private set; }
    public string Field4 { get; private set; }
    public string Field5 { get; private set; }
    public string Field6 { get; private set; }
    public string Field7 { get; private set; }
    public string Field8 { get; private set; }
    public string Field9 { get; private set; }
}

Drop a DataGridView on a form and run this:

// Create a bunch of Record objects.  Note: r1-f3 = record 1, field 3.
List<Record> recordList = new List<Record> { new Record("r1-f1,r1-f2,r1-f3,r1-f4,r1-f5,r1-f6,123"), 
                                             new Record("r2-f1,r2-f2,r2-f3,r2-f4,r2-f5,r2-f6,456"), 
                                             new Record("r3-f1,r3-f2,r3-f3,r3-f4,r3-f5,r3-f6,789")};
dataGridView1.DataSource = recordList;

Note that this is extremely fragile code and you'll want to do almost everything I show here differently in a production application. It does show what I mean though.


First you get the CSV file data into a Data Table and in the next step you put a loop and parse the value column vise and ex: if(dataTable.Row[index][7]==123; then splite the value into an array then set the array value to data Table

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜