Skip Navigation LinksHome > Articles > ADO.NET > How to handle MS-SQL RAISERROR using SqlConnection InfoMessage event

How to handle MS-SQL RAISERROR using SqlConnection InfoMessage event

How to handle MS-SQL RAISERROR using SqlConnection InfoMessage event

By gaonkaramit   On   Wednesday, 30 September 2009

Page Views : 796   |   Technologies : ADO.NET

Rating : Rated :
0

Introduction

This article explains about capturing stored procedure's RAISERROR statements from .Net application.

Implementation

Stored Procedure:
/*This stored procedure updated user table if userid is > 0 else it will raise error for invalid userid*/
CREATe PROCEDURE [dbo].[UpdateUser]
(
         @UserId int,  
         
@UserName VarChar(50),  
         
@Details VarChar(100)
)
AS
BEGIN
    
If @UserId <= 0
     BEGIN
          RAISERROR
('UserId invalid! it should be greater then zero', 16, 1)
     END
     ELSE
     BEGIN
          UPDATE
Users SET UserName = @UserName, Details = @Details
          WHERE UserId = @UserId
     END
END

 

Now to handle this code in your user interface you should use following technique.

 

C# Code:

//Declare variable to store exception

private Exception _sqlInfoEx = null;

 

/// <summary>

/// SqlInfoMessageEventHandler for handling raise error excpetions

/// </summary>

/// <param name="sender">object</param>

/// <param name="e">SqlInfoMessage EventArgs</param>

public void OnSqlInfoMessageEventHandler(object sender,
        SqlInfoMessageEventArgs e)

{

    //checks for any errors.

    if (e.Errors.Count > 0)

    {

        StringBuilder _sbError = new StringBuilder();

        foreach (SqlError _error in e.Errors)

        {

            _sbError.AppendLine(_error.Number.ToString() + " = " +        
                                
_error.Message);

        }                

        _sqlInfoEx = new Exception(_sbError.ToString());

    }

}

 

/// <summary>

/// Update user button click event

/// </summary>

/// <param name="sender">object</param>

/// <param name="e">event arguments</param>

private void btnUpdateUser_Click(object sender, EventArgs e)

{

    _sqlInfoEx = null;

    try

    {

        string _strConn = @"Data Source=.\SQLEXPRESS;"

                            +"Initial Catalog=Student;User ID=sa";        
        using (SqlConnection conn = new SqlConnection(_strConn))

        {                    

            //this event will execute if there are any
            //information coming from the sql server

            conn.InfoMessage += new

                        SqlInfoMessageEventHandler(OnSqlInfoMessageEventHandler);

            conn.Open();

            

            SqlCommand _cmd = new SqlCommand("UpdateUser", conn);

            _cmd.CommandType = CommandType.StoredProcedure;

            _cmd.Parameters.Add(new SqlParameter("@UserId",SqlDbType.Int));

            _cmd.Parameters[0].Value = 0;

            _cmd.Parameters.Add(new SqlParameter("@UserName",SqlDbType.VarChar,50));

            _cmd.Parameters[1].Value = "gaonkaramit";

            _cmd.Parameters.Add(new SqlParameter("@Details", SqlDbType.VarChar, 100));

            _cmd.Parameters[1].Value = "some details";

 

            int _result = _cmd.ExecuteNonQuery();

 

            //checking for exception

            if (_sqlInfoEx != null)

            {

                throw _sqlInfoEx;

            }

                    

        }

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, "Error");

    }

            

}

 

Hope this helps you..

cheers

amit


Keywords :
Tags :
Rate This Article :

Comments :

# 1 Annonymous Wrote on 01/07/2010


Good article. Thanks for your help!



# 2 donepudi_4u Wrote on 08/05/2010


good article... simple way of doing is write stored procedure using try and catch block and then directly display error message.. for more info check out here http://blog.sqlauthority.com/2007/04/11/sql-server-2005-explanation-of-trycatch-and-error-handling/



Write a Comment / Question / Feedback ...


User Login
Username :
Password :
Register Login

Forgot Password


Related Articles