0

我正在尝试仅导出 datagridview 上选定的复选框项目。我当前的代码可以工作,但问题是它导出了所有内容,我可以在导出的 csv 文件中看到 True/False 值,但是对于我来说,我无法弄清楚如何只导出真实值和不是一切。下面列出了示例代码。

private void GetCellData()
    {
        string data = "";
        string userDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        TextWriter tw = new StreamWriter(userDesktop + "\\" + "export.csv");

        // Count each row in the datagrid
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {

            if (dataGridView1.Rows[i].Cells["Selection_Box"].Value != null &&
                (bool)dataGridView1.Rows[i].Cells["Selection_Box"].Value)
            {
                foreach (DataGridViewCell cell in dataGridView1.Rows[i].Cells)
                {
                    data += (cell.Value + ",");
                }
                data += "\n";
            }               
            else
            {
                continue;
            }
        }
        tw.WriteLine(data, "data");
        tw.Close();
    }

数据网格“Selection_Box”上的复选框是 DataGridViewCheckBoxColumn。ExampleExport 只是链接到一个名为“Export”的按钮。当用户在数据网格中选择一个复选框并单击“导出”时,一个 .csv 文件将转储到桌面,其值类似于下面列出的值。

True ,3,1,Piping,Manual,RTD,2,45 Ax,
True ,4,1,Piping,Manual,RTD,2,60 Ax,
True,5,1,Piping,Manual,RTD,1.5,45 C ,
False,6,1,Piping,Manual,RTD,2,45 Axe,
False,8,1,Piping,Manual,RTD,1.5,45 C,
False,29,1,Piping,Manual,RTD,2,45 C,

编辑:感谢您为我指出正确的方向,非常感谢。我最终将 if 语句调整为:

if (dataGridView1.Rows[i].Cells["Selection_Box"].Value != null &&
                (bool)dataGridView1.Rows[i].Cells["Selection_Box"].Value)

它现在正在转储选定的值。

4

3 回答 3

2

在第一个 for 块中是这样的......

if(((bool)dataGridView1.Rows[i].Cells[0]) == true)
{
    // Loop through and get the values
    foreach (DataGridViewCell cell in dataGridView1.Rows[i].Cells)
    {
        data = data + (cell.Value + ",");
    }
    data += "\n";
}
else
{
    // else block not really necessary in this case, but illustrates the point....
    continue;
}
于 2011-06-16T11:22:33.743 回答
2

您应该检查 CheckBox 列中的值,例如

if((bool) row.Cells["Column7"] as DataGridViewCheckBoxCell).FormattedValue)

仅当为 true 时,您才附加该行的值

于 2011-06-16T11:23:34.480 回答
0

也可以这样确认是否属实

if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Selection_Box"].Value) == true)
于 2016-02-23T17:44:07.323 回答