Frage

I'm trying to export only the selected checkbox items on a datagridview. The current code I have works, but the problem is it exports everything, I'm able see the True/False values in the exported csv file but for the life of me I can't figure out how to export only the true values and not everything. Example code is listed below.

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();
    }

The checkbox on the datagrid "Selection_Box" is a DataGridViewCheckBoxColumn. ExampleExport is just linked to a button called "Export". When the user selects a checkbox in the datagrid and clicks "Export" a .csv file is dumped to the desktop with values similar to those listed below.

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 Ax,
False,8,1,Piping,Manual,RTD,1.5,45 C,
False,29,1,Piping,Manual,RTD,2,45 C,

EDIT: Thanks for pointing me in the right direction it's very much appreciated. I ended up tweaking the if statement to:

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

It's now dumping the selected values.

War es hilfreich?

Lösung

You should check for the values in the CheckBox column, something like

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

Only if true then you append the values of the row

Andere Tipps

something like this within the first for block....

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;
}

You can confirm whether it is true also in this way

if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Selection_Box"].Value) == true)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top