2013-04-03 64 views
0

我一直在尋找幾個小時的方法來將我的char數組直接加載到動態表中,然後加載到數據網格視圖中。將數組加載到數據表

嘗試了幾種方法,但總是有一些工作不按計劃進行。

通緝:將數組逐行寫入表中,從一個單元跳到另一個單元。

private void btn_okay(object sender, EventArgs e) 
{ 
    //reading the strings from the two text boxes 
    Char[] ArrayUp = rtb_up.Text.ToCharArray(); 
    Char[] ArrayDown = rtb_down.Text.ToCharArray(); 
    Char[] ArrayEnd = new Char [ArrayUp.Length * ArrayDown.Length]; 

    //comparison of the two char arrays and filling the new char array 
    Int32 I = 0; 

    for (Int32 C = 0; C < ArrayDown.Length; C++) 
    { 
     for (Int32 D = 0; D < ArrayUp.Length; D++) 
     { 
      if (ArrayDown[C] == ArrayUp[D]) 
      { 
       ArrayEnd[I] = '+' ; 
       I ++; 
      } 
      else 
      { 
       ArrayEnd[I] = '-' ; 
       I ++; 
      } 
     } 
    } 

    //creation of data table 
    DataTable Table = new DataTable(); 

    for (Int32 E = 0; E < ArrayUp.Length; E++) 
     Table.Columns.Add("", typeof(Char)); 

    for (Int32 R = 0; R < ArrayDown.Length; R++) 
     Table.LoadDataRow(ArrayEnd[R], LoadOption.OverwriteChanges()); 

    //OverwriteChanges won't work 
    dgv_main.AutoGenerateColumns = true; 
    dgv_main.DataSource = Table; 

} 

回答

2

修訂答:

string arrayUp = "ABBAAAABABAAAB"; // Example value for rtb_up.Text 
string arrayDown = "ABABAAABAB"; // Example value for rtb_down.Text 

DataTable dataTable = new DataTable(); 

// Add variable number of columns, depending on the length of arrayUp 
for (int i = 0; i < arrayUp.Length; i++) 
    dataTable.Columns.Add(""); 

// Iterate through the "rows" first 
for (int i = 0; i < arrayDown.Length; i++) 
{ 
    DataRow dataRow = dataTable.NewRow(); 

    // Then iterate through the "columns" 
    for (int j = 0; j < arrayUp.Length; j++) 
    { 
     if (arrayDown[i] == arrayUp[j]) 
      dataRow[j] = "+"; 
     else 
      dataRow[j] = "-"; 
    } 

    dataTable.Rows.Add(dataRow); 
} 

dgv_main.AutoGenerateColumns = true; 
dgv_main.DataSource = dataTable; 

這會給你一個情節酷似您發佈的屏幕截圖 - 無論一個A或B相交,會有一個加號(+)。它們不相交的地方會有一個負號( - )。

重要的是要注意,字符串本質上是一個Char [],所以不需要將您的TextBox值作爲Char []。

這是否讓你有你所需要的?

+0

這並不完全解決我的問題。我想將char數組加載到現有的表中,或者在存儲數組被填充時創建一個。數字或行和列不是靜態的,否則我可能會減少戲劇。 – MeepMania 2013-04-04 20:14:46

+0

我的示例不要求行數或列數是靜態的。行或列的數量完全取決於數組的長度。在你的情況下,它將是'rtb_up.Text'或'rtb_down.Text'的長度。爲了演示目的,我僅填充了特定值的陣列。 – McCee 2013-04-04 21:20:09

+0

它可能有助於查看將存儲在ArrayUp和ArrayDown數組中的一些示例值以及如何在DataGridView中查看這些值。 – McCee 2013-04-04 21:31:00