C#分隔符没有显示

时间:2017-06-20 00:42:29

标签: c# datagridview

我正在尝试使用datagridview分隔值来连接。不幸的是,我迷失了使用字符串连接。谢谢,如果有人能纠正我的错误。

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);
}

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

答案 2 :(得分:0)

String.Join用于连接数组。您只是将字符串添加到另一个字符串。使用标准连接运算符+

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

还要考虑这会导致您的消息以逗号开头,可以像下面这样修复:

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

当然,您可以将行转换为数组,然后使用String.Join,但我没有看到任何值。

相关问题