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

时间:2014-08-27 09:10:26

标签: c# exception exception-handling

我的班级

 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;
     }

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

我的button_click功能是

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;
        }
}

2 个答案:

答案 0 :(得分:2)

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

话虽这么说,我会在单独的方法中处理检查和插入,并在click事件处理程序中捕获异常 - 让一个方法只有一个责任:

    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;
        }           
    }

答案 1 :(得分:0)

Catch(Exception e)
{
Label.Text= e.Message;
}