[asp.net] Using the Web.Config to set up my SQL database connection string?

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

This question is related to asp.net sql sql-server sql-server-2008 web-config

The answer is


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

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" />

Add this to your web config and change the catalog name which is your database name:

  <connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;"/></connectionStrings>

Reference System.Configuration assembly in your project.

Here is how you retrieve connection string from the config file:

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

http://www.connectionstrings.com is a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.


If you use the Connect to Database under tools in Visual Studio, you will be able to add the name of the Server and database and test the connection. Upon success you can copy the string from the bottom of the dialog.


Your best bet, starting fresh like you are, is to go grab the enterprise library. They have a configuration tool you can use to wire everything up for you nicely.

They also have a data access application block which is very useful and documentation filled with good samples.

http://www.microsoft.com/downloads/details.aspx?FamilyId=90DE37E0-7B42-4044-99BE-F8ECFBBC5B65&displaylang=en


Web.config file

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS

Here is the connectionString in the web config file which you can add:

<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>

Place is just above the system.web tag.

Then you can call it by:

connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?

Examples related to web-config

No assembly found containing an OwinStartupAttribute Error IIS Config Error - This configuration section cannot be used at this path How to enable GZIP compression in IIS 7.5 how to set start page in webconfig file in asp.net c# Authentication issue when debugging in VS2013 - iis express Forms authentication timeout vs sessionState timeout Specified argument was out of the range of valid values. Parameter name: site Access-control-allow-origin with multiple domains "An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..." ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d