我正在尝试仅导出 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)
它现在正在转储选定的值。