SqlDataSource.ConnectionString Propriété

Définition

Obtient ou définit la chaîne de connexion propre au fournisseur ADO.NET utilisée par le contrôle SqlDataSource pour se connecter à une base de données sous-jacente.

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

Valeur de propriété

Chaîne spécifique au fournisseur de données .NET Framework que le SqlDataSource utilise pour se connecter à la base de données SQL qu’il représente. La valeur par défaut est une chaîne vide ("").

Exemples

Cette section contient deux exemples de code. Le premier exemple de code montre comment définir la ConnectionString propriété pour qu’elle se connecte à une base de données Microsoft SQL Server et affiche les résultats de la SelectCommand propriété dans un GridView contrôle. Le deuxième exemple de code illustre un scénario plus complexe, où un SqlDataSource contrôle est utilisé pour afficher et mettre à jour des données dans une base de données Microsoft Access protégée par mot de passe. Dans chaque cas, l’élément connectionStrings du fichier Web.config s’affiche en premier, suivi de la page ASP.NET qui contient le SqlDataSource contrôle.

L’exemple de code suivant montre comment définir la ConnectionString propriété pour qu’elle se connecte à une base de données SQL Server et affiche les résultats de la SelectCommand propriété dans un GridView contrôle.

<%@ 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>

L’exemple de code suivant illustre un scénario plus complexe que l’exemple de code précédent, où un SqlDataSource contrôle est utilisé pour afficher et mettre à jour des données dans une base de données Access protégée par mot de passe. Étant donné que le SqlDataSource est utilisé avec Access, la ProviderName propriété est définie sur le System.Data.OleDb fournisseur et la ConnectionString propriété est définie sur une chaîne de connexion appropriée pour une base de données Access partagée UNC. Un GridView contrôle affiche les commandes avec des dates d’expédition. Vous pouvez mettre à jour une commande en cochant la case case activée appropriée, puis en cliquant sur le bouton Mettre à jour.

Important

Cet exemple inclut un mot de passe en texte brut uniquement à des fins d’illustration. Dans une application de production, les chaînes de connexion qui incluent des mots de passe doivent être chiffrées. Pour plus d’informations, consultez Protection des informations de connexion.

<%@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>

Remarques

Le SqlDataSource contrôle peut être utilisé avec divers fournisseurs ADO.NET et la syntaxe de la chaîne de connexion utilisée pour se connecter à une source de données sous-jacente est spécifique au fournisseur.

Lorsque vous configurez un SqlDataSource contrôle, vous définissez la ProviderName propriété sur le type de base de données (la valeur par défaut est System.Data.SqlClient) et vous définissez la ConnectionString propriété sur une chaîne de connexion qui inclut les informations nécessaires pour se connecter à la base de données. Le contenu d’une chaîne de connexion diffère selon le type de base de données auquel le contrôle de source de données accède. Par exemple, le SqlDataSource contrôle nécessite un nom de serveur, un nom de base de données (catalogue) et des informations sur l’authentification de l’utilisateur lors de la connexion à un SQL Server. Pour plus d’informations sur le contenu des chaînes de connexion, consultez la ConnectionString propriété de la SqlConnection classe, ConnectionString la propriété de la OracleConnection classe, ConnectionString la propriété de la OleDbConnection classe ou la ConnectionString propriété de la OdbcConnection classe.

Si vous modifiez la ConnectionString propriété, l’événement DataSourceChanged est déclenché, ce qui entraîne la reliure de tous les contrôles liés au SqlDataSource contrôle.

Important

Pour plus d’informations sur le stockage d’une chaîne de connexion, consultez Guide pratique pour sécuriser les chaînes de connexion lors de l’utilisation de contrôles de source de données.

S’applique à

Voir aussi