[Solved] How can we set catch exception in a label?


It’s not the prettiest of code. Returning a string as a kind of status code is generally bad practice, because you don’t know the range of possible values which can be returned, and what they mean. At the very least consider integer or even enum (which is named).

That being said, I would handle the check and the insert in separate methods, and catch the exception in the click event handler – let a single method have a single responsibility:

    private void AddCountry(string country, string id)
    {
        using (SqlConnection conn = new SqlConnection())
        {
            string sql = string.Format("INSERT INTO Country (Id, Country) VALUES ('{0}', '{1}')", id, country);
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.ExecuteNonQuery();
            }
        }
    }

    private bool Exists(string country, string id)
    {
        using (SqlConnection conn = new SqlConnection())
        {
            string sql = "SELECT Count(*) FROM Country WHERE Country='" + country + "'";
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                int count = (int)cmd.ExecuteScalar();

                return count >= 1;
            }
        }
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (Exists(txtcountry.Text, txtid.Text))
            {
                Response.Write("<script>alert('Country Already Exist!!!!')</script>");
            }
            else
            {
                AddCountry(txtcountry.Text, txtid.Text);
                Response.Write("<script>alert('Country Added Succesfully')</script>");
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }           
    }

0

solved How can we set catch exception in a label?