This is to get the last inserted id from the database table when the ID is Auto-increment.
string InsertedId = "";
RowAffected = cmd.ExecuteCommand();
string query="SELECT LAST_INSERT_ID() FROM studinfo";
if (RowAffected > 0)
cmd= new MySqlCommand(query, Con);
InsertedId = cmd.ExecuteScalar();
This is another way to get the lastinserted from the table.
string filename = txtImage.Text;
byte[] imagedata;
fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
imagedata = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
string query = "SELECT max(ID) FROM studinfo";
cmd = new MySqlCommand(query, con);
InsertedId = cmd.ExecuteScalar();
if (InsertedId == "")
{
InsertedId = 1;
}
else
{
InsertedId = InsertedId + 1;
}
string cmdText = "Insert into studinfo values(@ID,@First,@Last,@address,@Image)";
cmd = new MySqlCommand(cmdText, con);
cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(InsertedId));
cmd.Parameters.AddWithValue("@First", txtFirstName.Text);
cmd.Parameters.AddWithValue("@Last", txtLastName.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Image", imagedata);
int rowaffected = cmd.ExecuteNonQuery();
if (rowaffected > 0)
{
MessageBox.Show("Inserted sucessfully");
Clear();
txtFirstName.Focus();
}
Hope this helps you.