SqlDataSource.ConnectionString Property

Definition

Gets or sets the ADO.NET provider-specific connection string that the SqlDataSource control uses to connect to an underlying database.

public:
 virtual property System::String ^ ConnectionString { System::String ^ get(); void set(System::String ^ value); };
public virtual string ConnectionString { get; set; }
member this.ConnectionString : string with get, set
Public Overridable Property ConnectionString As String

Property Value

A .NET Framework data provider-specific string that the SqlDataSource uses to connect to the SQL database that it represents. The default is an empty string ("").

Examples

This section contains two code examples. The first code example demonstrates how to set the ConnectionString property to connect to a Microsoft SQL Server database and display the results of the SelectCommand property in a GridView control. The second code example demonstrates a more complex scenario, where a SqlDataSource control is used to display and update data in a password-protected Microsoft Access database. In each case, the connectionStrings element of the Web.config file is shown first, followed by the ASP.NET page that contains the SqlDataSource control.

The following code example demonstrates how to set the ConnectionString property to connect to a SQL Server database and display the results of the SelectCommand property in a GridView control.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT FirstName, LastName, Title FROM Employees">
      </asp:SqlDataSource>

      <asp:GridView
          id="GridView1"
          runat="server"
          DataSourceID="SqlDataSource1">
      </asp:GridView>

    </form>
  </body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT FirstName, LastName, Title FROM Employees">
      </asp:SqlDataSource>

      <asp:GridView
          id="GridView1"
          runat="server"
          DataSourceID="SqlDataSource1">
      </asp:GridView>

    </form>
  </body>
</html>

The following code example demonstrates a more complex scenario than the preceding code example, where a SqlDataSource control is used to display and update data in a password-protected Access database. Because the SqlDataSource is used with Access, the ProviderName property is set to the System.Data.OleDb provider, and the ConnectionString property is set to an appropriate connection string for a UNC-shared Access database. A GridView control displays orders with shipment dates. You can update an order by checking the appropriate check box, and then clicking the Update button.

Important

This example includes a password in plain text only for illustration purposes. In a production application, connection strings that include passwords should be encrypted. For more information, see Protecting Connection Information.

<%@Page  Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
private void UpdateRecords(Object source, EventArgs e)
{
  // This method is an example of batch updating using a
  // data source control. The method iterates through the rows
  // of the GridView, extracts each CheckBox from the row and, if
  // the CheckBox is checked, updates data by calling the Update
  // method of the data source control, adding required parameters
  // to the UpdateParameters collection.
  CheckBox cb;
  foreach(GridViewRow row in this.GridView1.Rows) {
    cb = (CheckBox) row.Cells[0].Controls[1];
    if(cb.Checked) {
      string oid = (string) row.Cells[1].Text;
      MyAccessDataSource.UpdateParameters.Add(new Parameter("date",TypeCode.DateTime,DateTime.Now.ToString()));
      MyAccessDataSource.UpdateParameters.Add(new Parameter("orderid",TypeCode.String,oid));
      MyAccessDataSource.Update();
      MyAccessDataSource.UpdateParameters.Clear();
    }
  }
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->

      <asp:SqlDataSource
        id="MyAccessDataSource"
        runat="server"
        ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
        ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
        SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
        UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
        <SelectParameters>
          <asp:QueryStringParameter Name="empId" QueryStringField="empId" />
        </SelectParameters>
      </asp:SqlDataSource>

      <asp:GridView
        id ="GridView1"
        runat="server"
        DataSourceID="MyAccessDataSource"
        AllowPaging="True"
        PageSize="10"
        AutoGenerateColumns="False">
          <columns>
            <asp:TemplateField HeaderText="">
              <ItemTemplate>
                <asp:CheckBox runat="server" />
              </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Order" DataField="OrderID" />
            <asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
            <asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
            <asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
          </columns>
      </asp:GridView>

      <asp:Button
        id="Button1"
        runat="server"
        Text="Update the Selected Records As Shipped"
        OnClick="UpdateRecords" />

      <asp:Label id="Label1" runat="server" />

    </form>
  </body>
</html>
<%@Page  Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Sub UpdateRecords(source As Object, e As EventArgs)

  ' This method is an example of batch updating using a
  ' data source control. The method iterates through the rows
  ' of the GridView, extracts each CheckBox from the row and, if
  ' the CheckBox is checked, updates data by calling the Update
  ' method of the data source control, adding required parameters
  ' to the UpdateParameters collection.

  Dim cb As CheckBox
  Dim row As GridViewRow

  For Each row In GridView1.Rows

    cb = CType(row.Cells(0).Controls(1), CheckBox)
    If cb.Checked Then

      Dim oid As String
      oid = CType(row.Cells(1).Text, String)

      Dim param1 As New Parameter("date", TypeCode.DateTime, DateTime.Now.ToString())
      MyAccessDataSource.UpdateParameters.Add(param1)

      Dim param2 As New Parameter("orderid", TypeCode.String, oid)
      MyAccessDataSource.UpdateParameters.Add(param2)

      MyAccessDataSource.Update()
      MyAccessDataSource.UpdateParameters.Clear()
    End If
  Next
End Sub ' UpdateRecords
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->

      <asp:SqlDataSource
        id="MyAccessDataSource"
        runat="server"
        ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
        ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
        SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
        UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
        <SelectParameters>
          <asp:QueryStringParameter Name="empId" QueryStringField="empId" />
        </SelectParameters>
      </asp:SqlDataSource>

      <asp:GridView
        id ="GridView1"
        runat="server"
        DataSourceID="MyAccessDataSource"
        AllowPaging="True"
        PageSize="10"
        AutoGenerateColumns="False">
          <columns>
            <asp:TemplateField HeaderText="">
              <ItemTemplate>
                <asp:CheckBox runat="server" />
              </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Order" DataField="OrderID" />
            <asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
            <asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
            <asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
          </columns>
      </asp:GridView>

      <asp:Button
        id="Button1"
        runat="server"
        Text="Update the Selected Records As Shipped"
        OnClick="UpdateRecords" />

      <asp:Label id="Label1" runat="server" />

    </form>
  </body>
</html>
<script runat="server">
private void UpdateRecords(Object source, EventArgs e)
{
  // This method is an example of batch updating using a
  // data source control. The method iterates through the rows
  // of the GridView, extracts each CheckBox from the row and, if
  // the CheckBox is checked, updates data by calling the Update
  // method of the data source control, adding required parameters
  // to the UpdateParameters collection.
  CheckBox cb;
  foreach(GridViewRow row in this.GridView1.Rows) {
    cb = (CheckBox) row.Cells[0].Controls[1];
    if(cb.Checked) {
      string oid = (string) row.Cells[1].Text;
      MyAccessDataSource.UpdateParameters.Add(new Parameter("date",TypeCode.DateTime,DateTime.Now.ToString()));
      MyAccessDataSource.UpdateParameters.Add(new Parameter("orderid",TypeCode.String,oid));
      MyAccessDataSource.Update();
      MyAccessDataSource.UpdateParameters.Clear();
    }
  }
}
</script>
<script runat="server">
Private Sub UpdateRecords(source As Object, e As EventArgs)

  ' This method is an example of batch updating using a
  ' data source control. The method iterates through the rows
  ' of the GridView, extracts each CheckBox from the row and, if
  ' the CheckBox is checked, updates data by calling the Update
  ' method of the data source control, adding required parameters
  ' to the UpdateParameters collection.

  Dim cb As CheckBox
  Dim row As GridViewRow

  For Each row In GridView1.Rows

    cb = CType(row.Cells(0).Controls(1), CheckBox)
    If cb.Checked Then

      Dim oid As String
      oid = CType(row.Cells(1).Text, String)

      Dim param1 As New Parameter("date", TypeCode.DateTime, DateTime.Now.ToString())
      MyAccessDataSource.UpdateParameters.Add(param1)

      Dim param2 As New Parameter("orderid", TypeCode.String, oid)
      MyAccessDataSource.UpdateParameters.Add(param2)

      MyAccessDataSource.Update()
      MyAccessDataSource.UpdateParameters.Clear()
    End If
  Next
End Sub ' UpdateRecords
</script>

Remarks

The SqlDataSource control can be used with a variety of ADO.NET providers and the syntax of the connection string that is used to connect to an underlying data source is specific to the provider.

When you configure a SqlDataSource control, you set the ProviderName property to the type of database (the default is System.Data.SqlClient), and you set the ConnectionString property to a connection string that includes information that is required in order to connect to the database. The contents of a connection string differ depending on what type of database the data source control is accessing. For example, the SqlDataSource control requires a server name, database (catalog) name, and information about how to authenticate the user when connecting to a SQL Server. For information about the contents of connection strings, see the ConnectionString property for the SqlConnection class, ConnectionString property for the OracleConnection class, ConnectionString property for the OleDbConnection class, or the ConnectionString property for the OdbcConnection class.

If you change the ConnectionString property, the DataSourceChanged event is raised, causing any controls that are bound to the SqlDataSource control to rebind.

Important

For information about storing a connection string, see How To: Secure Connection Strings when Using Data Source Controls.

Applies to

See also