Kevin Lee
Kevin Lee

Reputation: 27

c# - Splitting a string, then writing into datagridview rows

I have a serialport which reads a string such as: "11,22,33,44", however the number of separators differ etc: "11,22,33,44,55,66"

I want to split the string and then write the separated strings into a datagridview, I have tried:

string[] array = _text.Split(',');
table.Rows.Add(array[0], array[1], array[2], array[3]);
datagridview1.DataSource = table;

However, the problem here is that the arrays may come in a different amount. Is there a way to do this?

Thanks for any help

Upvotes: 0

Views: 2167

Answers (4)

D Stanley
D Stanley

Reputation: 152556

You don't have to add each item as a parameter to Add. The Add method takes an array as the parameter, so you can just do:

string[] array = _text.Split(',');
table.Rows.Add(array);
datagridview1.DataSource = table;

And it will add columns corresponding to the number of items in your array.

If you want to add multiple rows with a varying number of columns, you will need to check the size of the array first, then add columns to the DataTable as necessary, otherwise you will get an exception if the number of items in the array exceeds the number of columns in the DataTable.

Upvotes: 2

Abdul Mateen Mohammed
Abdul Mateen Mohammed

Reputation: 1894

You can directly add the array as the row to the DataGridView, check the below code snippet.

namespace SO
{
    using System;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            var input = "11,22,33,44";
            string[] array = input.Split(',');
            dataGridView1.Rows.Add(array);
        }
    }
}

enter image description here

Upvotes: 0

Thili77
Thili77

Reputation: 1095

For do this you can parse into string list..

_text = "11,22,33,44,55,66";

List<String> str_list = new List<String>();
str_list = _text.Split(',').ToList();
foreach(var item in str_list)
{
    table.Rows.Add(item);
}
datagridview1.DataSource = table;

This will work for you..

Upvotes: 0

Mayank
Mayank

Reputation: 8852

All you need to do is iterate over array and add each item.

string[] array = _text.Split(',');
foreach(var item in array)
{
     table.Rows.Add(item);
}
datagridview1.DataSource = table;

Upvotes: 1

Related Questions