如何从数据库中显示错误消息作为对用户的警报

时间:2015-02-19 17:51:01

标签: c# sql asp.net webforms

我有一个包含其他表的几个外键的表,并防止它们从这些表中被删除的数据被用作RESTRICT ON的另一个表中的外键...但是如何显示此错误通过警报向用户发送?

protected void ListSourceClient_Deleting(object sender, SqlDataSourceCommandEventArgs e)
    {
        try
        {
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            string check = "DELETE FROM Cliente WHERE [Id] = @Id";
            SqlCommand cmd = new SqlCommand(check, conn);
            conn.Open();
            conn.Close();
            e.Cancel = true;

        }
        catch (Exception)
        {
            Response.Write("<script>alert('You can't delete this client because it's used!');</script>");
        }
    }

2 个答案:

答案 0 :(得分:0)

这取决于您希望向最终用户显示的异常类型。

通常,这是如何从后面的代码向最终用户显示警报消息。

protected void DeleteButton_Click(object sender, EventArgs e)
{
    try
    {
        // Simulating an exception
        throw new Exception("You can't delete this client because it's used!");
    }
    catch (Exception ex)
    {
        this.ClientScript.RegisterStartupScript(this.GetType(), "alert" + UniqueID,
            "alert(\"" + ex.Message + "\");", true);

        // You need to use ScriptManager if you use ajax.
        /*ScriptManager.RegisterStartupScript(this, this.GetType(), "alert" + UniqueID,
"alert(\"" + ex.Message + "\");", true);*/
    }
}

仅供参考: 我只是注意到您在邮件中使用了单引号,因此我用双引号替换了警告信息的单引号。

答案 1 :(得分:0)

试试这个

试         {

        string deleteCommand = "DELETE FROM [Kit] WHERE [KitID] = @KitID";

        SqlDataSource1.DeleteCommand = deleteCommand;

    }
    catch (SqlException SqlEx)
    {

        switch (SqlEx.Number)
        {
            case 547:
                // Do something.
                ErrorLabel.Text = "Error: "there is some relation"
                break;
            default:
                throw;
        }
    }