自动编号和数据表与 dbnull 异常

发布于 2024-12-02 16:42:46 字数 1575 浏览 8 评论 0原文

我正在对一个数据表做一些工作,我用一个由访问数据库制成的 oledbdataadapter 填充了该数据表。我偶然发现了这个错误:

原来我的表有这样的结构: 身份证号--> autonumber(PK)

lazos_>text

Asociaciones->text

,当我填充数据表时,所有值都会传递给它,所有正确值都不会出现任何问题。我插入一个新行,如“插入行”部分所示。

我这样做是假设我的 pk 将在行创建时插入“自动编号”,但显然它没有这样做,因为当我循环遍历行时,我得到一个“无效的转换异常”,对象无法从 DBNull 转换为其他类型。”

我可以向该列插入一个 id 值,但是当我将 dt 更新到数据库时,它不会产生错误,因为我无法知道最后一行是创建的吗?或者我会这样做吗

?假设在我的数据表中最后一个ID是50,但是在数据库中y之前做了一条ID为“51”的记录,但后来删除了它,如果我根据我的dt信息插入51,它会给出错误,对吧?

    //// INSERT ROW
    DataRow newRow = Tabla_Cods_Proy.NewRow();
    newRow["Lazos"] = textBox1.Text ;
    newRow["Asociaciones"] = textBox2.Text;
    Tabla_Cods_Proy.Rows.Add(newRow);
    MessageBox.Show("Enhorabuena!");


//CHECK ID's            
    for (int i = 0; i < Tabla_Cods_Proy.Rows.Count; i++)
    {
        if (Tabla_Cods_Proy.Rows[i].RowState != DataRowState.Deleted)
        {
            if (Tabla_Cods_Proy.Rows[i]["Lazos_asociados"].ToString() == "")
            {

                listBox7.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Cliente"]);
                listBox8.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Inelectra"]);
                ID_Cods_Proy_Sin_Asociar.Add(Convert.ToInt32(Tabla_Cods_Proy.Rows[i]["ID"]));

            }
            else
            {
                listBox3.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Cliente"]);
                listBox4.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Inelectra"]);
                ID_Cods_Proy_Asociados.Add(Convert.ToInt32(Tabla_Cods_Proy.Rows[i]["ID"]));
            }
        }

i was doing some work on a datatable i filled with a oledbdataadapter made from an access database. and i stumbled upon this error:

Turns out that my table has this structure:
ID --> autonumber(PK)

lazos_>text

Asociaciones->text

and when i fill my datatable all values pass to it without any problems with all the correct values. I insert a new row like shown on the "insert row" part.

i do this asumming that my pk will instert the "autonumber" on row creation, but apparently it is not doing it because when i loop trought the rows i get a "invalid cast exception" with a Object cannot be cast from DBNull to other types."

I COULD insert an id value to the column, but when i update my dt to my database wont it create an error, because i have no way of knowing wich was the last row created?, or do i?

for example lets say in my datatable the last ID is 50, but on the database y previously made a record with id "51" but then erased it, if i inserted 51 based on my dt info, it would give an error right?

    //// INSERT ROW
    DataRow newRow = Tabla_Cods_Proy.NewRow();
    newRow["Lazos"] = textBox1.Text ;
    newRow["Asociaciones"] = textBox2.Text;
    Tabla_Cods_Proy.Rows.Add(newRow);
    MessageBox.Show("Enhorabuena!");


//CHECK ID's            
    for (int i = 0; i < Tabla_Cods_Proy.Rows.Count; i++)
    {
        if (Tabla_Cods_Proy.Rows[i].RowState != DataRowState.Deleted)
        {
            if (Tabla_Cods_Proy.Rows[i]["Lazos_asociados"].ToString() == "")
            {

                listBox7.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Cliente"]);
                listBox8.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Inelectra"]);
                ID_Cods_Proy_Sin_Asociar.Add(Convert.ToInt32(Tabla_Cods_Proy.Rows[i]["ID"]));

            }
            else
            {
                listBox3.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Cliente"]);
                listBox4.Items.Add(Tabla_Cods_Proy.Rows[i]["Cod_Inelectra"]);
                ID_Cods_Proy_Asociados.Add(Convert.ToInt32(Tabla_Cods_Proy.Rows[i]["ID"]));
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

┊风居住的梦幻卍 2024-12-09 16:42:46

我曾经遇到过类似的问题。您需要做的是将其插入表后检索该列的新标识@@IDENTITY。您可以使用 RowUpdated 事件来做到这一点。

以下是 MSDN 页面(与您的情况类似,请参见页面底部):

    public static void Main() 
    {
       //...connecting to access db and getting data to datatable...
       // ...
       // Adding a new row to datatable.
       DataRow newRow = catDS.Tables["Categories"].NewRow();
       newRow["CategoryName"] = "New Category";
       catDS.Tables["Categories"].Rows.Add(newRow);

       // Include an event to fill in the Autonumber value.
       catDA.RowUpdated += new OleDbRowUpdatedEventHandler(OnRowUpdated);

    }

    protected static void OnRowUpdated(object sender, OleDbRowUpdatedEventArgs args)
    {
       // Include a variable and a command to retrieve the identity value from the Access database.
       int newID = 0;
       OleDbCommand idCMD = new OleDbCommand("SELECT @@IDENTITY", nwindConn);

       if (args.StatementType == StatementType.Insert)
       {
          // Retrieve the identity value and store it in the CategoryID column.
          newID = (int)idCMD.ExecuteScalar();
          args.Row["CategoryID"] = newID;
       }
    }

I had once similiar problem. What you need to do is that you retrieve the new identity @@IDENTITY of this column once you insert it into table. You can do that by using RowUpdated event.

Here is quick example from MSDN page (similiar to your case, see bottom of the page):

    public static void Main() 
    {
       //...connecting to access db and getting data to datatable...
       // ...
       // Adding a new row to datatable.
       DataRow newRow = catDS.Tables["Categories"].NewRow();
       newRow["CategoryName"] = "New Category";
       catDS.Tables["Categories"].Rows.Add(newRow);

       // Include an event to fill in the Autonumber value.
       catDA.RowUpdated += new OleDbRowUpdatedEventHandler(OnRowUpdated);

    }

    protected static void OnRowUpdated(object sender, OleDbRowUpdatedEventArgs args)
    {
       // Include a variable and a command to retrieve the identity value from the Access database.
       int newID = 0;
       OleDbCommand idCMD = new OleDbCommand("SELECT @@IDENTITY", nwindConn);

       if (args.StatementType == StatementType.Insert)
       {
          // Retrieve the identity value and store it in the CategoryID column.
          newID = (int)idCMD.ExecuteScalar();
          args.Row["CategoryID"] = newID;
       }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文