Wednesday, March 10, 2010

How to Run Time Dynamically Build ConnectionString in Asp.Net




Please visit my new Web Site WWW.Codedisplay.com



Asp.net gives developers a class to build runtime dynamically connectionstring named SqlConnectionStringBuilder. Here in this article I will show you by an example. Please have a look at the below code example which will help you to understand how one can build dynamically connectionstring with less error possibilities.














Code Example:
using System;
using System.Data;
using System.Data.SqlClient;

public partial class Connectionstringbuilder : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Build connectionstring
            SqlConnectionStringBuilder ConnBuilder = new SqlConnectionStringBuilder();

            ConnBuilder.DataSource = @".\SQLExpress"; // Name of the Sql Server instance
            ConnBuilder.InitialCatalog = "TestDB"; // Database Name
            ConnBuilder.UserID = "sa";
            ConnBuilder.Password = "your password";
            ConnBuilder.ConnectTimeout = 0;
            ConnBuilder.IntegratedSecurity = false;


            //How to use
            DataTable dt;
            String SQL = "SELECT Name,Description,Size,Color From Product  Order BY Name";
            using (SqlConnection Conn = new SqlConnection(ConnBuilder.ConnectionString))
            {
                using (SqlCommand comm = new SqlCommand(SQL, Conn))
                 {
                     Conn.Open();
                     using (SqlDataAdapter da = new SqlDataAdapter(comm))
                     {
                         dt = new DataTable("tbl");
                         da.Fill(dt);
                     }
                 }            
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}
Hope now you can dynamically build your connection string if needed.

0 comments:

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash