Oleg.Budeanu
Oleg.Budeanu

Reputation: 35

split string by character and add to different columns in DataGridView in c#

I have this code :

string strdata = Encoding.Unicode.GetString(buffer);
char[] splitchar = new Char[] { '\x00' };
string[] assetdata = strdata.Split(splitchar, strdata.Length);

Buffer is a text data which goes as one row and consists of 4 types of variables. You can see example of Encoded in Unicode buffer following this link : http://pastebin.com/ScdGX8it So there are 4 types of data here which needs to be filled into DataGridView rows separated by 4 columns , so it can me sorted and manipulated after. Assetdata is array with this data separated by each value as a single element , but i need to group them - that is the main problem. Thanks.

Upvotes: 1

Views: 1651

Answers (2)

tinstaafl
tinstaafl

Reputation: 6948

Here's one way without LINQ, that uses a datatable as the datasource for the datagridview.

        DataTable dt = new DataTable("T1");
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("A"), new DataColumn("B"), new DataColumn("C"), new DataColumn("D")});
        for (int i = 0; i < assetdata.Length; i += 4)
        {
            dt.Rows.Add(new string[]{assetdata[i],assetdata[i+1],assetdata[i+2],assetdata[i+3]});
        }
        dataGridView1.DataSource = dt;

This way you can modify the datatable and update the datagridview, which will probably give you more options since this fits in more with how the datagridviewwas was designed.

Upvotes: 1

Cam Bruce
Cam Bruce

Reputation: 5689

LINQ is your friend. Go through the tutorials on grouping. It should be pretty easy, since you already have a string[]. Once you're done with your query, call the ToIEnumerable() extension method to bind to a DataGridView.

http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

Upvotes: 0

Related Questions