#954 - Impostare a runtime la query di selezione con SqlDataSource

Nello script #877 abbiamo visto come impostare a runtime il valore dei parametri delle query eseguite da un SqlDataSource.
Analogamente, è possibile impostare la query. Prendiamo ad esempio il seguente SqlDataSource:

<asp:SqlDataSource ID="GameSqlDataSource" runat="server"
  ConnectionString="<%$ ConnectionStrings:ConnectionStringDataBase %>"
  SelectCommand="SELECT [ID], [NomeGioco], [IDGenere] FROM [Giochi] WHERE ([IDGenere] = @IDGenere)"
  OnSelecting="GameSqlDataSource_Selecting" >
  <SelectParameters>
   <asp:ControlParameter ControlID="DropDownList1" Name="IDGenere" type="Int32" />
  </SelectParameters>
</asp:SqlDataSource>

Una semplice query estrae il nome del gioco in base ad una delle categorie disponibili, selezionata meditante l'uso di una DropDownList, ma in alcuni casi può essere necessario selezionare tutti i giochi indipendentemente dalla categoria.

Creiamo un event handler per l'evento Selecting, in cui la funzione riceve un oggetto del tipo SqlDataSourceSelectingEventArgs, così che mediante la proprietà Command, di tipo DbCommand, imposteremo la query ed elimineremo i parametri non più necessari.

protected void GameSqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
  if (DropDownList1.SelectedValue == "0")
  {
    e.Command.CommandText = "SELECT [ID], [NomeGioco], [IDGenere] FROM [Giochi]";
    e.Command.Parameters.Clear();
  }
}

IL CONTENUTO
CONNECTIONSTRING
Ti serve una stringa di connessione ad un database?
PROVIDER ASP.NET 2.0, 3.5 e 4.0

Seleziona il tuo provider per avere il web.config pronto per Membership, Roles e Profile API.

SCRIPT VIA E-MAIL

Iscriviti alle nostre newsletter unoscript@lgiorno e Xcript per ricevere gli script via e-mail.

MEDIA
IN EVIDENZA
MISC