//窗体初始化
void MainFormLoad(object sender, EventArgs e)
{
//建立一个DataTable
DataTable dt = new DataTable();
dt.Columns.Add("id",typeof(int));
dt.Columns.Add("name",typeof(string));
dt.Columns.Add("sex",typeof(string));
//建立绑定
BindingSource bs=new BindingSource();
bs.DataSource= dt;
this.dataGridView1.DataSource=bs;
this.bindingNavigator1.BindingSource=bs;
//设置主键
dt.PrimaryKey = new DataColumn[] { dt.Columns["id"] };
this.dataGridView1.DataSource = dt.DefaultView; //绑定文本框
this.textBox1.DataBindings.Add("Text",bs,"id");
this.textBox2.DataBindings.Add("Text",bs,"name");
this.textBox3.DataBindings.Add("Text",bs,"sex");
}两个问题请教大家:
1,在bindingNavigator1连续点两次增加记录的按钮(增加两次空白记录)则出现:Exception System.Data.NoNullAllowedException was thrown in debuggee:
Column 'id' does not allow nulls.
2,在textBox1中输入相同的数字""11",并点bindingNavigator1的增加记录按钮(增加两次相同id)则出现:Exception System.Data.ConstraintException was thrown in debuggee:
Column 'id' is constrained to be unique. Value '11' is already present.出现这两个异常后程序退出,我想捕捉这个两个异常,避免程序退出,请问有什么方法吗?多谢。
void MainFormLoad(object sender, EventArgs e)
{
//建立一个DataTable
DataTable dt = new DataTable();
dt.Columns.Add("id",typeof(int));
dt.Columns.Add("name",typeof(string));
dt.Columns.Add("sex",typeof(string));
//建立绑定
BindingSource bs=new BindingSource();
bs.DataSource= dt;
this.dataGridView1.DataSource=bs;
this.bindingNavigator1.BindingSource=bs;
//设置主键
dt.PrimaryKey = new DataColumn[] { dt.Columns["id"] };
this.dataGridView1.DataSource = dt.DefaultView; //绑定文本框
this.textBox1.DataBindings.Add("Text",bs,"id");
this.textBox2.DataBindings.Add("Text",bs,"name");
this.textBox3.DataBindings.Add("Text",bs,"sex");
}两个问题请教大家:
1,在bindingNavigator1连续点两次增加记录的按钮(增加两次空白记录)则出现:Exception System.Data.NoNullAllowedException was thrown in debuggee:
Column 'id' does not allow nulls.
2,在textBox1中输入相同的数字""11",并点bindingNavigator1的增加记录按钮(增加两次相同id)则出现:Exception System.Data.ConstraintException was thrown in debuggee:
Column 'id' is constrained to be unique. Value '11' is already present.出现这两个异常后程序退出,我想捕捉这个两个异常,避免程序退出,请问有什么方法吗?多谢。
解决方案 »
- 手机软件课题,一起来
- 异步加载数据,方法2和4造成界面假死,方法3造成DataGridView滚动条不可用,那位大侠能帮我解决一下。
- 如何去掉多余的空格
- 智能手机怎么安装.net精简框架?
- 如何从剪切板获取一个OLE对象(OLE对象已经复制到剪切板了)
- 字符串拆分,请高手帮忙解决一下!!
- 怎么在winform中动态打开xtrareporting的模板 要求代码详细
- 求教问题,最好用正则解决
- 关于静态方法访问非静态成员的问题!!
- 在北京寻找工作ing......
- 如何用在窗体加载时给iframe中的div加上样式
- 两个pictureBox叠加遮挡,要点击下面的pictureBox,在线站等~!!!!
2、主键字段不能重复,你添加记录时,需要判断设置的主键值是否已经存在;
综上两点,你每次添加记录时,获取已有记录的最大id值,然后将这个最大id值+1赋值给你添加记录的主键字段就可以了
可以,但是在并发高一点的时候会有bug,要加锁。不管怎样,数据库中的约束是起码的设计
如果不能确定代码具体哪段出现异常,就把main里面的都用try包住,然后catch exception了之后throw出来,再return一下,就不会程序异常退出了