C#get access 2010 autonumber

时间:2014-01-30 09:51:15

标签: c# oledb ms-access-2010 autonumber

您好我提交了一个表单进行访问,但希望在我提交后,在文本框中显示访问分配的自动编号。在我的下面,任何建议都会很棒!

string cmdstr = "Insert into  TaskPerformed(TaskType,OtherType,Analyst,DateCompleted)Values(@b,@c,@d,@e)";
string query2 = "Select @@IDENTITY";

OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con1);
OleDbCommand cmdNewID = new OleDbCommand("SELECT @@IDENTITY", con1);//

con1.Open();

cmd.CommandText = query2;
com.ExecuteNonQuery();
con1.Close();

label16.Text = cmdNewID.ToString();

1 个答案:

答案 0 :(得分:3)

看起来您遇到的问题是因为您没有执行第二个命令...而且您在使用之前关闭了连接

using(OleDbCommand cmdNewID = new OleDbCommand("SELECT @@IDENTITY", con1))
{
    con1.Open();

    cmd.CommandText = query2;
    com.ExecuteNonQuery();

    label16.Text = cmdNewID.ExecuteScalar();
}