C#正在导出选定的DataGridViewCheckBoxCell

本文关键字:DataGridViewCheckBoxCell | 更新日期: 2023-09-27 17:59:13

我试图只导出数据网格视图上的选定复选框项目。我目前的代码可以工作,但问题是它导出了所有内容,我可以在导出的csv文件中看到True/False值,但就我而言,我不知道如何只导出True值,而不是所有内容。下面列出了示例代码。

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文件将转储到桌面,其值与下面列出的值类似。

,3,1,管道,手动,RTD,2,45 Ax,
,4,1,管道,手动,RTD,2,60 Ax,
True,5,1,管道,手动,RTD,1.5,45 C,
假,6,1,管道,手动,RTD,2,45 Ax,
假,8,1,管道,手动,RTD,1.5,45 C,
假,29,1,管道,手动,RTD,2,45C,

编辑:非常感谢你给我指明了正确的方向。我最终将if语句调整为:

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

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

C#正在导出选定的DataGridViewCheckBoxCell

您应该检查CheckBox列中的值,类似

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

只有当为true时,才附加行的值

第一个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;
}

您也可以通过这种方式确认是否为真

if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Selection_Box"].Value) == true)
相关文章:
  • 没有找到相关文章