0

I have a csv spec file I read into a List of strings. Then add it to a datagridview and add a checkbox column. I want to check all of the checkboxes, but nothing has worked. Tried looping through each row and setting the value to true, also tried to set the default values needed row event but no luck. Any ideas?

DataTable dtSpecs = new DataTable();

string[] tmpHeaders = specList[0].Split(','); 

foreach (var header in tmpHeaders)
{
    dtSpecs.Columns.Add(header, typeof(string));
}

for (int i = 1; i < specList.Count; i++)
{
    dtSpecs.Rows.Add(specList[i].Split(','));
}

dataGridView2.DataSource = dtSpecs;

DataGridViewCheckBoxColumn ckb2 = new DataGridViewCheckBoxColumn();
ckb2.HeaderText = "Enable";
ckb2.ValueType = typeof(bool);
dataGridView2.Columns.Insert(0, ckb2);

//This didn't work
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
    dataGridView2.Rows[i].Cells[0].Value = true;
}

//This way also didn't work
foreach (DataGridViewRow row in dataGridView2.Rows)
{
    row.Cells[0].Value = true;
}

//Also tried this but still nothing checked
private void dataGridView2_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    e.Row.Cells[0].Value = true;
}
2
  • see this: stackoverflow.com/questions/13242861/… Commented Sep 2, 2015 at 23:26
  • This code, work for me, can you please provide more code about your load page or other method in your page please. Commented Sep 2, 2015 at 23:32

1 Answer 1

1

Don't mix UI and data. Since you are using a DataTable as a data storage for the grid, don't create a grid column, add a DataColumn to the data table instead. Like:

var dt = new DataTable();
dt.Columns.Add("Enable", typeof(bool));
var names = specList[0].Split(','); 
for (int c = 0; c < names.Length; c++)
    dt.Columns.Add(names[c]);
for (int i = 1; i < specList.Count; i++)
{
    var dr = dt.Rows.Add();
    dr[0] = true;
    var values = specList[i].Split(',');
    for (int c = 0; c < values.Length; c++)
        dr[1 + c] = values[c];  
}
dataGridView2.DataSource = dt;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.