Your below code is returning the error.
nt KeyId = int.Parse("0" + ds.Tables[0].Rows[0][0].ToString());
Change your last Using block with below code.
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
con.Close();
if(ds!=null && ds.Tabels[0].Rows.Count>0)
{
int KeyId = int.Parse("0" + ds.Tables[0].Rows[0][0].ToString());
}
}
Basically your query is returning no rows.