110,533
社区成员
发帖
与我相关
我的任务
分享
public bool? IsActive{get;set;}
public DateTime? CreateTime{get;set;}
class TestObj
{
public DateTime? Birthday { get; set; }
public bool? IsMan { get; set; }
public double? Age { get; set; }
public string Name { get; set; }
}
private TestObj to;
private Binding bind;
private void Form4_Load(object sender, EventArgs e)
{
to = new TestObj();
to.Birthday = null;
bind = new Binding("Value", to, "Birthday");
//bind.ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;
//bind.DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;
//textBox1.DataBindings.Add(bind);
bind.FormattingEnabled = true;//设置允许格式化
bind.NullValue = DateTime.Now.AddDays(100);//如果绑定的属性为空值就取这一个
//bind.DataSourceNullValue = DateTime.Now;
this.dateTimePicker1.DataBindings.Add(bind);
}
设置允许格式化,和NullValue 就可以了。
我之前测试的都是文本框的绑定,由于它的属性Text需要的是一个string所以无论怎么设值都没问题的。
你这儿绑定的属性Value,需要的是一个DateTime类型的,所以存在一个类型转换的问题。
public class Person
{
public DateTime? CreateTime { get; set; }
}
Person person = new Person();
dateTimePicker1.DataBindings.Add("Value", person, "CreateTime");
报“System.FormatException: 无法将值格式化为所需的类型。” class TestObj
{
public DateTime? Birthday { get; set; }
public bool? IsMan { get; set; }
public double? Age { get; set; }
public string Name { get; set; }
}
private TestObj to;
private void Form4_Load(object sender, EventArgs e)
{
to = new TestObj { Name = "zhangsan", Age = 20.5, IsMan = false, Birthday = DateTime.Now };
textBox1.DataBindings.Add("Text", to, "Birthday");
}
各种类型都试了,都可以绑定成功的。不知道你那儿是个什么情况。
var data = new List<TestObj> {
new TestObj { Date = null },
new TestObj { Date = DateTime.Now }
};
this.dataGridView1.DataSource = data;
//this.dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
this.textBox1.DataBindings.Add("Text", this.dataGridView1.DataSource, "Date");
this.dateTimePicker1.DataBindings.Add("Text", this.dataGridView1.DataSource, "Date");
class TestObj
{
public int? Age { get; set; }
public string Name { get; set; }
}
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
TestObj to = new TestObj { Age = 10, Name = "zhangsan" };
this.textBox1.DataBindings.Add("Text", to, "Age");
}
}
我试了一下,怎么一切正常呢?弹出界面后,文本框正常显示:10