数据网格视图中复选框列的默认值 [英] Checkbox column default value in data grid view

查看:91
本文介绍了数据网格视图中复选框列的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

请勿将UI和数据。由于您将 DataTable 用作网格的数据存储,因此不要创建网格列,而是添加 DataColumn 改为数据表。像这样:

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;

这篇关于数据网格视图中复选框列的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆