Using the Web.Config to set up my SQL database connection string?

128,385

Solution 1

Here's a great overview on MSDN that covers how to do this.

In your web.config, add a connection string entry:

<connectionStrings>
  <add 
    name="MyConnectionString" 
    connectionString="Data Source=sergio-desktop\sqlexpress;Initial 
    Catalog=MyDatabase;User ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

Let's break down the component parts here:

Data Source is your server. In your case, a named SQL instance on sergio-desktop.

Initial Catalog is the default database queries should be executed against. For normal uses, this will be the database name.

For the authentication, we have a few options.

User ID and Password means using SQL credentials, not Windows, but still very simple - just go into your Security section of your SQL Server and create a new Login. Give it a username and password, and give it rights to your database. All the basic dialogs are very self-explanatory.

You can also use integrated security, which means your .NET application will try to connect to SQL using the credentials of the worker process. Check here for more info on that.

Finally, in code, you can get to your connection string by using:

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString

Solution 2

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class form_city : System.Web.UI.Page
{
    connection con = new connection();
    DataTable dtable;
    string status = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        TextBoxWatermarkExtender1.WatermarkText = "Enter State Name !";        
        if (!IsPostBack)
        {
            status = "Active";
            fillgrid();
            Session.Add("ope", "Listing");
        }
    }
    protected void fillgrid()
    {
        //Session.Add("ope", "Listing");
        string query = "select *";
        query += "from State_Detail where Status='" + status + "'";
        dtable = con.sqlSelect(query);
        grdList.DataSource = dtable;
        grdList.DataBind();
        lbtnBack.Visible = false;
    }
    protected void grdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdList.PageIndex = e.NewPageIndex;
        string operation = Session["ope"].ToString();
        if (operation == "ViewLog")
            status = "Inactive";
        else if (operation == "Listing")
            status = "Active";
        fillgrid();
    }
    public string GetImage(string status)
    {
        if (status == "Active")
            return "~/images/green_acti.png";
        else
            return "~/images/red_acti.png";
    }
    protected void grdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string st = "Inactive";
        int State_Id = Convert.ToInt32(grdList.DataKeys[e.RowIndex].Values[0]);
        string query = "update State_Detail set Status='" + st + "'";
        query += " where State_Id=" + State_Id;
        con.sqlInsUpdDel(query);
        status = "Active";
        fillgrid();
    }    
    protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            string query = "select * ";
            query += "from State_Detail where State_Id=" + e.CommandArgument;
            dtable = con.sqlSelect(query);
            grdList.DataSource = dtable;
            grdList.DataBind();
            lbtnBack.Visible = true;
        }
    }
    protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        Session.Add("ope", "Listing");
        if (txtDepId.Text != "")
        {
            string query = "select * from State_Detail where State_Name like '" + txtDepId.Text + "%'";
            dtable = con.sqlSelect(query);
            grdList.DataSource = dtable;
            grdList.DataBind();
            txtDepId.Text = "";
        }
    }
    protected void grdList_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int State_Id = Convert.ToInt32(grdList.DataKeys[e.NewEditIndex].Values[0]);
        Session.Add("ope", "Edit");
        Session.Add("State_Id", State_Id);
        Response.Redirect("form_state.aspx");
    }

    protected void grdList_Sorting(object sender, GridViewSortEventArgs e)
    {
        string operation = Session["ope"].ToString();
        if (operation == "ViewLog")
            status = "Inactive";
        else if (operation == "Listing")
            status = "Active";

        string query = "select * from State_Detail";
        query += " where Status='" + status + "'";
        dtable = con.sqlSelect(query);
        DataView dview = new DataView(dtable);
        dview.Sort = e.SortExpression + " asc";
        grdList.DataSource = dview;
        grdList.DataBind();
    }
}
<asp:Image ID="imgGreenAct" ImageUrl='<%# GetImage(Convert.ToString(DataBinder.Eval(Container.DataItem, "Status")))%>' AlternateText='<%# Bind("Status") %>' runat="server" />
Share:
128,385
Sergio Tapia
Author by

Sergio Tapia

I'm a 21 year old professional programmer that likes to read about a wide range of things related to programming. Currently, I'm pounding away at ASP.Net MVC2.

Updated on July 09, 2022

Comments

  • Sergio Tapia
    Sergio Tapia almost 2 years

    Can anyone help me out please? I'm confused.

    I want to set up my connection string so I can just call it from my Web.Config file.

    I need a way to call it from my code, please make a little example. :(

    I also need help on setting up the Web.Config file.

    I don't know what properties to use. Here's a screenshot of what my credentials are. I have no password set up for Windows. I'm really lost here.

    alt text

  • Sergio Tapia
    Sergio Tapia over 14 years
    Thanks for the link but it only shows how to invoke the connection string from code, not how to find the connection string and set it up. :(
  • Sergio Tapia
    Sergio Tapia over 14 years
    I'm confused you say: "Database=yourBDName" and "InitialCatalog=yourDBName". Which is which?
  • waqasahmed
    waqasahmed over 14 years
    same.. just write the same for both :)
  • Sergio Tapia
    Sergio Tapia over 14 years
    Thanks a million. Incredible answer and I've learned how to use it! :D