我们如何在标签中设置catch异常

本文关键字:设置 catch 异常 标签 我们 | 更新日期: 2023-09-27 18:19:30

我的类

 public string Countryadd(string country, string id)
     {
         string data = "0";
         try
         {

             string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition
             SqlDataReader dr = conn.query(qry1);
             if (dr.Read())
             {
                 return data = "1";
             }
             else 
             {
                 string qry = "insert into Country values('" + id + "','" + country + "')";
                 conn.nonquery(qry);
                 return data = "3";
             }
         }
         catch (Exception ex)
         {
             string x = ex.Message();
         }
         return data;
     }

这个字符串值我们如何在标签中设置

我的按钮点击功能是

protected void Button1_Click(object sender, EventArgs e)
    {
        string str = mas.Countryadd(txtcountry.Text, txtid.Text);
        if (str == "1")
        {
            Response.Write("<script>alert('Country Already Exist!!!!')</script>");
        }
        else if (str == "3")
        {
            Response.Write("<script>alert('Country Added Succesfully')</script>");
        }
        else
        {
            Label1.Text = str;
        }
}

我们如何在标签中设置catch异常

这不是最漂亮的代码。将字符串作为一种状态代码返回通常是不好的做法,因为您不知道可以返回的可能值的范围以及它们的含义。至少要考虑integer甚至enum(已命名)。

话虽如此,我将在单独的方法中处理检查和插入,并在点击事件处理程序中捕获异常——让一个方法有一个单一的责任:

    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;
        }           
    }
Catch(Exception e)
{
Label.Text= e.Message;
}