在特定行c#,asp.net之后插入记录 [英] insert record after particular row c#,asp.net

查看:82
本文介绍了在特定行c#,asp.net之后插入记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将记录插入到sql server 2008表中,使用c#asp.net,列值全部声明为nvarchar,第一列subid是主键。在我的代码中,我检索最后一个coulmn id,增加它并将其用作新记录的subid,当我插入记录时,它不会按顺序存储,而是存储在某处的中间。所以下次我尝试检索最后一个id列值(虽然我使用order by),它给出了现有的值,当递增时,会给出错误,重复值,不允许。

这是我检索最后一个id值的代码并增加它:



I want to insert records into the sql server 2008 table,using c# asp.net,the column values are all declared as "nvarchar",and the 1st column subid is the primary key.In my code,i retrieve the last coulmn id,increment it and use it as the subid for new record,when i insert a record,it does not get stored sequentially,instead it gets stored in the middle somewhere.So the next time i try to retrieve the last id column value(though i use "order by"),it gives the existing value,which when incremented,gives an error,"duplicate values,not allowed".
this is my code to retrieve the last id value and increment it:

SqlCommand myCommand = new SqlCommand("SELECT TOP 1 subid FROM subjects                         

ORDER BY subid DESC", con1);         

     reader = myCommand.ExecuteReader();
    if (reader.HasRows == false)
    {
        Label4.Text = "1";
        reader.Close();
    }
    else
    {
        while (reader.Read()) // if can read row from database
        {

            id = reader[0].ToString();

        }
        int n = Convert.ToInt32(id);
        int j = n + 1;
        Label4.Text = j.ToString();





我的插入代码是:



my insert code is:

SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 * FROM subjects ORDER BY       
subid DESC", con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet("subjects");
da.Fill(ds, "subjects");
DataRow row = ds.Tables["subjects"].NewRow(); 
row["subid"] = Label4.Text;
row["dept"] = (string)Session["deptmnt"];
row["yr"] = DropDownList2.SelectedValue;
row["sem"] = DropDownList3.SelectedValue;
row["subname"] = TextBox1.Text;
row["subcode"] = TextBox2.Text;

ds.Tables["subjects"].Rows.Add(row);
da.Update(ds, "subjects");

Label10.Visible = true;
con.Close();



如何将值插入最后一行,请帮助。


how do i make the value get inserted as the last row,pls help.

推荐答案

谢谢大家的回复:)我试过这个:

thank you all for your replies :) i tried this:
SELECT max(cast(subid as int)) FROM subjects



工作


it worked


这篇关于在特定行c#,asp.net之后插入记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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