2017-06-20 49 views
2

我試圖用分隔符連接datagridview的值。不幸的是,我迷失了使用字符串連接。謝謝,如果有人能糾正我的錯誤。C#分隔符不顯示

private void Button_Click(object sender, EventArgs e) 
{  
    string message = string.Empty; 

    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
     bool isSelected = Convert.ToBoolean(row.Cells["Column1"].Value); 
     if (isSelected) 
     { 
      message += String.Join(", ", row.Cells["pk_pspatitem"].Value.ToString()); 
     } 
    } 

    MessageBox.Show(message); 
} 
+1

分隔符將只顯示分離多個項目。如果只有一個,那麼它不會顯示 – Nkosi

回答

1

分隔符將僅顯示分隔多個項目。如果只有一個,那麼它不會顯示。

嘗試收集所有的值,然後使用帶有分隔符的String.Join

List<string> values = new List<string>(); 
foreach (DataGridViewRow row in dataGridView1.Rows) { 
    bool isSelected = Convert.ToBoolean(row.Cells["Column1"].Value); 
    if (isSelected) { 
     values.Add(row.Cells["pk_pspatitem"].Value.ToString()); 
    } 
} 
string message = String.Join(", ", values); 
MessageBox.Show(message); 
0

String.Join用於連接數組。你只是添加一個字符串到另一個字符串。使用標準連接運算符+

message += ", " + row.Cells["pk_pspatitem"].Value.ToString(); 

也可考慮,這將導致你的消息,開始用逗號,可固定這樣的:

MessageBox.Show(message.Substring(2)); 

當然,你可以在行轉換爲數組,然後用String.Join ,但我沒有看到任何價值。

4

或者你可以用LINQ查詢它:

string message = String.Join(", ", from DataGridViewRow r in dataGridView1.Rows 
            where true.Equals(r.Cells["Column1"].Value) 
            select r.Cells["pk_pspatitem"].Value); 

在C#7.0 pattern matching(自帶的Visual Studio 2017)

string message = String.Join(", ", from DataGridViewRow r in dataGridView1.Rows 
            where r.Cells["Column1"].Value is true 
            select r.Cells["pk_pspatitem"].Value); 
+0

我最喜歡你的答案,但我寧願看到'where(bool)r.Cells [「Column1」]。Value'。 「真實的等式」有點尷尬。 – Enigmativity

+0

@Enigmativity它是非常不尋常的,但在我看來,它是最安全的時候比較對象,可以是任何東西,包括null和DBNull.Value。它的確像'obj是bool &&(bool)obj == true'一樣。https://referencesource.microsoft.com/#mscorlib/system/boolean.cs,0bb4737ad44c98a4 – Slai

+0

不夠公平。這聽起來像是一個合理的方法。 – Enigmativity