【问题标题】:C# Exporting selected DataGridViewCheckBoxCellC# 导出选定的 DataGridViewCheckBoxCell
【发布时间】:2011-06-16 11:13:19
【问题描述】:

我正在尝试仅导出 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 文件将转储到桌面,其值类似于下面列出的值。

,3,1,管道,手动,RTD,2,45 Ax,
,4,1,管道,手动,RTD,2,60 Ax,
True,5,1,Piping,Manual,RTD,1.5,45 C,
False,6,1,管道,手动,RTD,2,45 斧头,
False,8,1,管道,手动,RTD,1.5,45 C,
False,29,1,管道,手动,RTD,2,45 C,

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

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

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

【问题讨论】:

    标签: c# datagridviewcheckboxcell


    【解决方案1】:

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

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

    只有当为真时,你才追加行的值

    【讨论】:

      【解决方案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;
      }
      

      【讨论】:

        【解决方案3】:

        这样也可以确认是否为真

        if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Selection_Box"].Value) == true)
        

        【讨论】:

          猜你喜欢
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          • 2010-12-06
          • 2021-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多