数据网格视图中的复选框列默认值

时间:2015-09-02 23:19:43

标签: c# checkbox datagridview

我有一个csv spec文件,我读入了一个字符串列表。然后将其添加到datagridview并添加复选框列。我想检查所有的复选框,但没有任何工作。尝试循环遍历每一行并将值设置为true,也尝试设置行事件所需的默认值但没有运气。有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

不要混用UI和数据。由于您使用DataTable作为网格的数据存储,因此不要创建网格列,而是将DataColumn添加到数据表中。喜欢:

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;