在datagridview中使用foreach获取字符串

时间:2014-03-02 12:13:23

标签: c# datagridview foreach getstring

我创建了一个函数,目的是向我创建的DataGrid显示连接的字符串:

  

file1.exe,file2.docx,file3.mp3

如何显示那种方式?我试过了,但是messagebox显示一个空字符串。

这是代码:

public void View()
{
    string namaFile = string.Empty;
    foreach (DataGridViewRow row in DGVDekripsi.Rows)
    {
       string NameFile = (string)row.Cells[0].Value;
       namaFile += NameFile + ",";
    }
    MessageBox.Show(namaFile);
}

1 个答案:

答案 0 :(得分:1)

我看到你的代码无效的唯一方法就是你的DataGridView中没有行,所以没有什么可以迭代的。即使你有几行而且它们都有空名,你至少会得到一个包含多个逗号的字符串。

此外,使用LINQ:

获取名称列表的方法稍微短一些
var allNames = string.Join(",",
               DGVDekripsi.Rows.Cast<DataRow>().Select(x => x.Field<string>(0)));