locked
Message RRS feed

  • Question

  • User-797751191 posted

    Hi

      I have below code . If both Record is Inserted & File successfully saved then then message should get displayed "Successsfully Done" else "Error message should get displayed". 

    string sql = "INSERT INTO tbl1 ([Id],[Name]) VALUES (@Id,@Name)";
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    SqlCommand cmd0 = new SqlCommand(sql, con);
                    cmd0.Parameters.AddWithValue("@Id", txtId.Text);
                    cmd0.Parameters.AddWithValue("@Name", txtName.Text);
    cmd0.CommandType = CommandType.Text;
                    cmd0.ExecuteNonQuery();

    fpUpload.SaveAs(Server.MapPath("~") + "/Attachment/" + nFile);

    Thanks

    Sunday, July 7, 2019 6:13 AM

All replies

  • User665608656 posted

    Hi jsshivalik,

    According to your description, if you want to display the error message,  you can use try-catch-finally grammar: try-catch-finally (C# Reference)

    I have made an example , you could refer to the following code:

     protected void Button1_Click(object sender, EventArgs e)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                conn.Open();
                try
                {
                    SqlCommand cmd = new SqlCommand("Insert into Test (Id,Name) values(@Id,@Name)", conn);
                    cmd.Parameters.AddWithValue("@Id", txtId.Text);
                    cmd.Parameters.AddWithValue("@Name", txtName.Text);
                    cmd.ExecuteNonQuery();
                    fpUpload.SaveAs(Server.MapPath("~") + "/Attachment/" + nFile);
                    StringBuilder builder = new StringBuilder();
                    builder.Append("<script language=JavaScript>alert(\"Successsfully Done!\")</script>");
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "SuccessAlert", builder.ToString());
    
                }
                catch (Exception ex)
                {
                    StringBuilder builder = new StringBuilder();
                    builder.Append("<script language=JavaScript>");
                    builder.Append("alert(\"" + ex.Message.Replace("\r\n", "") + "\")");
                    builder.Append("</script>");
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "FailAlert", builder.ToString());
                }
                finally
                {
                    conn.Close();
                    txtId.Text = "";
                    txtName.Text = "";
                }
    
    
            }

    The result of this work demo:

    Best Regards,

    YongQing.

    Monday, July 8, 2019 2:33 AM