17

When using SqlCommand to execute a non-query (such as a database restore), is it possible to programatically get the text that would normally be posted to the "Messages" tab if using the Management Studio? And if so how?

1 Answer 1

31

Yes, there's an event hook on the SqlCommand object called SqlInfoMessage, which you can hook into:

SqlConnection _con = new SqlConnection("server=.;database=Northwindintegrated Security=SSPI;");

_con.InfoMessage += new SqlInfoMessageEventHandler(_con_InfoMessage);

The event handler will look like this:

static void _con_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    string myMsg = e.Message;            
}

The "e.Message" is the message printed out to the message window in SQL Server Mgmt Studio.

Marc

Sign up to request clarification or add additional context in comments.

2 Comments

+1: Thsi is awesome. After using ADO.NET for so many years, this is the first time coming across this...
:-) Glad you like it ! .NET in general is soooo vast - everyone constantly learns and picks up new tricks :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.