当我单击保存按钮时,错误显示索引或主键不能包含空值。 [英] When i click the save button error shows Index or Primary Key cannot contain a Null Value.

查看:94
本文介绍了当我单击保存按钮时,错误显示索引或主键不能包含空值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据库设计如下



列数据类型

ID文本(主键)

教师代码文字

课程代码文字



设计如下;



Id Combobox

教师代码组合框

课程代码组合框



新保存清除(按钮)





新按钮代码如下;



Database Design as follows

Column Data Type
ID Text (Primary Key)
Faculty Code text
course Code text

design as follows;

Id Combobox
Faculty Code Combo box
Course Code Combo box

New Save Clear (Buttons)


New button code as follows;

private void Btn_New_Click(object sender, EventArgs e)
        {
            GFun.BindAccessConn();
            OleDbCommand cmd = new OleDbCommand("select MAX(ID) +1 from Tb_Faculty_Approval", GFun.OleDbCon);
            OleDbDataReader oledr = cmd.ExecuteReader();
            while (oledr.Read())
            {
                cb_id.Text = oledr[0].ToString().Trim();
            }

        }





ID是我编写代码的自动增量新按钮。



在数据库中我将​​ID设置为主键。



在运行模式下我点击新按钮,ID 1将出现。

在教师代码中选择教师

在课程代码中选择couse



然后当我点击保存按钮时,错误显示如下;







The ID is the auto increment for that i written a code in the new button.

In database i set ID as Primary key.

In the run mode i click the new button the ID 1 will appear.
In faculty Code select the faculty
In the Course Code Select the couse

Then when i click the Save Button the error shows as follows;


Index or Primary Key cannot contain  a Null Value.



新按钮代码中的问题是什么。



或者在ID栏中的数据库设计想要改变?



请帮帮我。



谢谢&问候,

Narasiman P.


what is the problem in the New Button code.

Or in the database design in the ID column want to change?

please help me.

Thanks & Regards,
Narasiman P.

推荐答案

更好的自动增量方法是将标识设置为列。

使用此查询来更改列

The better way to auto increment ise set identity to the column.
use this query to alter your column
alter table table1 add col3 int identity(1,1)





现在你不需要插入这个值。每次插入新行,ID列增加1.



试试吧。



Now you do not need to insert this value.Each time new row inserted,ID column incremented by 1.

Try it.


你可以使用它......

You can use it...
public double maxid(string tablename)
      {
          double number = 0; ;
          SqlDataAdapter da = new SqlDataAdapter("select max(id) from " + tablename + " ", con);
          SqlDataAdapter da2 = new SqlDataAdapter("select * from " + tablename + " ", con);
          DataSet ds = new DataSet();
          DataSet ds2 = new DataSet();
          da.Fill(ds, tablename);
          da2.Fill(ds2, tablename);
          double num = ds2.Tables[0].Rows.Count;
          if (num.ToString() == "0")
          {
              number = 0;
          }
          else
          {
              number = Convert.ToDouble(ds.Tables[0].Rows[0][0]);
          }
          return (number);
      }





或者您可以检查max(id)是否为dbnull然后返回0 ....只从表名中选择max(id)



谢谢

Asp.Net C#帮助博客 [ ^ ]


这篇关于当我单击保存按钮时,错误显示索引或主键不能包含空值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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