2017-06-20 50 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