0

Hi I am submitting a form to access but want to get the access assigned auto number to display in a textbox after I submit. Below it was i have, any suggestions would be great!

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();
Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
hex c
  • 705
  • 2
  • 13
  • 22
  • 2
    You're not executing cmdNewId - that might help – Paul Michaels Jan 30 '14 at 09:53
  • Also, your parameter placeholders should just be question marks (`?`) and you don't seem to be creating any `.Parameter`s or assigning values to them. – Gord Thompson Jan 30 '14 at 10:09
  • @GordThompson You can call the parameters anything you like IMHO, it is just that the names are not used, only the order. I prefer to use 'real' names rather than ?, it makes it easier to see where I am going. – Fionnuala Jan 30 '14 at 10:14
  • @Remou True, but [this](http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters%28v=vs.110%29.aspx) says that "the question mark (?) placeholder must be used". So, even though `@names` actually do work, I maintain that `?` *should* be used (and comments placed beside the `.Add` or `.AddWithValue` statements to indicate what the value is) to prevent the false impression that the names have any real functional significance. – Gord Thompson Jan 30 '14 at 10:26
  • @GordThompson That is a reasonable argument, but it is clear that the help page is wrong, `must` suggests that nothing else will work, but that is not true. – Fionnuala Jan 30 '14 at 10:49
  • @Remou I agree, "the question mark (?) placeholder should be used" would have been a better choice of words on that page. – Gord Thompson Jan 30 '14 at 12:53

1 Answers1

3

It looks like the problem you're having is because you're not executing the second command... and you're closing the connection before using it

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

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

    label16.Text = cmdNewID.ExecuteScalar();
}
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269