经过大量的搜索之后,我无法找到解决此问题的方法。我已经使用如下列表成功设置了DatagridView的数据源。
班级
public class ChannelInfo
{
[Browsable(false)]
[DisplayName("ChannelId")]
public int channelId { get; set; }
[DisplayName("Channel")]
public string sysName { get; set; }
[DisplayName("Display Name")]
public string dispName { get; set; }
[DisplayName("Unit")]
public string unit { get; set; }
[DisplayName("Divide By")]
public int divideBy { get; set; }
[DisplayName("YAxis")]
public string yAxis { get; set; }
[DisplayName("Min Scale")]
public int scaleMin { get; set; }
[DisplayName("Max Scale")]
public int scaleMax { get; set; }
[DisplayName("Colour")]
public string colour { get; set; }
[DisplayName("Set Point")]
public double setPoint { get; set; }
[DisplayName("Limit(+/-)")]
public double? limit { get; set; }
[DisplayName("MKT")]
public bool? IncludeInMKT { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public ChannelInfo()
{
}
/// <summary>
/// Copy constructor to create a copy of another object
/// </summary>
/// <param name="ci"> and object of the type ChannelInfo whos copy is to be created</param>
public ChannelInfo(ChannelInfo ci)
{
channelId = ci.channelId;
sysName = ci.sysName;
dispName = ci.dispName;
unit = ci.unit;
divideBy = ci.divideBy;
yAxis = ci.yAxis;
scaleMin = ci.scaleMin;
scaleMax = ci.scaleMax;
colour = ci.colour;
setPoint = ci.setPoint;
limit = ci.limit;
IncludeInMKT = ci.IncludeInMKT;
}
}
设置网格的数据源
static List<ChannelInfo> chInfoList;
dgvChannels.DataSource = chInfoList;
使用设计器将数据网格的最后一列的类型设置为DataGridViewCheckBoxColumn。数据网格显示除最后一个布尔字段IncludeInMkt之外的所有数据。它显示文本值(True / False),而我希望它显示为带有chInfoList中相应值的复选框。我还在设计器中将TrueValue设置为True,将FalseValue设置为False。
我在哪里出错,请提出。
DataGridView
将为DataGridViewCheckBoxColumn
属性生成bool
。但是对于bool?
属性,它将生成DataGridViewTextBoxColumn
。
您可以在设计时或运行时修复问题,方法是将生成的列替换为DataGridViewCheckBoxColumn
,并将其ThreeState
属性设置为true。
示例-在DataGridView中显示Nullable<bool>
的复选框
将其作为模型:
public class Test
{
public int MyProperty1 { get; set; }
public bool? MyProperty2 { get; set; }
}
我们可以将bool?
属性的生成列更改为树状复选框框:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.dataGridView1.DataSource = new BindingList<Test>() {
new Test(){ MyProperty1 = 1, MyProperty2= null},
new Test(){ MyProperty1 = 2, MyProperty2= true},
new Test(){ MyProperty1 = 3, MyProperty2= false},
};
UseCheckBoxForNullableBool(dataGridView1);
}
public void UseCheckBoxForNullableBool(DataGridView g)
{
g.Columns.Cast<DataGridViewColumn>()
.Where(x => x.ValueType == typeof(bool?))
.ToList().ForEach(x =>
{
var index = x.Index;
g.Columns.RemoveAt(index);
var c = new DataGridViewCheckBoxColumn();
c.ValueType = x.ValueType;
c.ThreeState = true;
c.DataPropertyName = x.DataPropertyName;
c.HeaderText = x.HeaderText;
c.Name = x.Name;
g.Columns.Insert(index, c);
});
}
注意:如果您想显示ComboBox
或bool
列的bool?
,请查看this post,它对bool
属性的作用相同,并对其进行一些更改以支持bool?
好。