PDA

View Full Version : سوال: return primary key from insert command in c#



train_fox
دوشنبه 09 اسفند 1389, 12:03 عصر
private int InsertInvoice()
{
SqlCeConnection Conn = new SqlCeConnection(connectString);
SqlCeCommand CMD = new SqlCeCommand();
CMD.Connection = Conn;
CMD.CommandType = CommandType.Text;
CMD.CommandText =
"INSERT INTO InvoiceTB ( " +
"InvoiceDate, InvoiceType, ShopID, ContactID)" +
"VALUES ( " +
"@InvoiceDate, @InvoiceType, @ShopID, @ContactID); "+
"SELECT SCOPE_IDENTITY()";
CMD.Parameters.AddWithValue("@InvoiceDate",InvoiceDate);
CMD.Parameters.AddWithValue("@InvoiceType",1);//for buy
CMD.Parameters.AddWithValue("@ShopID",shopID);
CMD.Parameters.AddWithValue("@ContactID",contactID);

Conn.Open();
invoiceID = int.Parse(CMD.ExecuteScalar().ToString());
Conn.Close();

MessageBox.Show(invoiceID.ToString(), "ID");

return invoiceID; //InvoiceTB primary key added
}

میشه بگید مشکل چیه؟