2017-01-09 164 views
0

我有一個串行端口讀取一個字符串,如:「11,22,33,44」,但分隔符的數量不同等:「11,22,33, 44,55,66"c# - 分割一個字符串,然後寫入datagridview行

我要拆分的字符串,然後寫入字符串分隔成一個DataGridView,我曾嘗試:

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

然而,這裏的問題是,陣列可能會在一不同的金額。 有沒有辦法做到這一點?

感謝您的任何幫助

回答

2

您不必將每個項目作爲參數添加到Add。該Add方法接受一個數組作爲參數,所以你可以這樣做:

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

而且這將增加相應的數組中的項數列。

如果你想用一個不同的列數增加行,你需要先檢查數組的大小,然後將列添加到DataTable必要的,否則你會得到,如果數量異常數組中項目的數量超過DataTable中的列數。

+0

謝謝!我的問題是我做了table.Rows.Add(i ++,array);其中「我」是索引的整數。發生了什麼事情,它在表格單元格中顯示「System.String []」。 –

+0

使用foreach,你可以輕鬆做到這一點比。 – Thili77

1

所有你需要做的是遍歷數組並添加每個項目。

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

爲了做到這一點,你可以解析成字符串列表..

_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; 

這會爲你工作..

0

您可以直接在數組作爲行添加到DataGridView,請檢查下面的代碼片段。

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