February 24 2014

ASP.net MSSQL connection test

Tagged Under : ,

asp.net
I am making a little code to test the functionality server with MSSQL Database connection. The test code was develop with asp.net C#.

If the script successful connect with MSSQL Database it will display message like below:
TESTS COMPLETED SUCCESSFULLY!.
Else, it will display
TESTS FAILED!

Server script:
<script runat="server">
    void DBTestTest_Click(object sender, EventArgs e) {
        string message = string.Empty;
        string Server = txtServer.Text.Trim();
        string Username = txtUsername.Text.Trim();
        string Password = txtPassword.Text.Trim();
        
        System.Data.IDbConnection con = null;
        con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = string.Format("Data Source={0};User ID={1};Password={2}", Server, Username, Password);
        
        try {
            con.Open();
            message += " Connection established.";
            con.Close();
            message += " Disconnecting from server.";
            message += " TESTS COMPLETED SUCCESSFULLY!.";
        } catch (Exception ex) {
            message += " " + ex.Message;
            message += " TESTS FAILED!";
        }
        
        Literal L = new Literal();
        L.Text = message;
        MessageHolder.Controls.Add(L);
    }
</script>

HTML form script:
<form id="form" runat="server">
<asp:PlaceHolder ID="MessageHolder" runat="server"></asp:PlaceHolder>
<h2>Test MSSQL Connection</h2>
<table border="0" >
    <tr>
        <td>Server:<td>
        <td><asp:TextBox ID="txtServer" Runat="Server" Columns="25" CssClass="input-text"></asp:TextBox></td>
    </tr>
    <tr>
        <td>Username:</td>
        <td><asp:TextBox ID="txtUsername" Runat="Server" Columns="25" CssClass="input-text"></asp:TextBox></td>
    </tr>
    <tr>
        <td>Password:</td>
        <td><asp:TextBox ID="txtPassword" Runat="Server" Columns="25" CssClass="input-text"></asp:TextBox></td>
    </tr>
    <tr>
        <td colspan="2">
            <button type="submit" value="" name="bname_ok" onserverclick="DBTestTest_Click" runat=server>Test Connection</button>
        </td>
    </tr>
</table>
</form>

You can download the completed code from HERE.

Make a Comment

*

code