Wednesday, March 21, 2012

Passing arrays as parameter (SqlDataSource)

My sql-string looks like this:
 SelectCommand="SELECT *FROM Table1WHERE Field1IN @.target"
And my parameter looks like this:
<asp:ControlParameter Name="target" ControlID="CheckBoxList1" PropertyName="SelectedValue" />

This code gives me a syntax error near @.target. Someone got a solution?

I wish I new how to do it with a Parameter, but I'm running into the same problem as you. However, here's an example on how to do it by simple modifying the CommandText during the SqlDataSource.Selecting event:

ASPX

<asp:checkboxlist id="lstProducts" runat="server" datasourceid="sdsProducts" datatextfield="ProductName"datavaluefield="ProductID" autopostback="True" onselectedindexchanged="lstProducts_SelectedIndexChanged"></asp:checkboxlist><asp:sqldatasource id="sdsProducts" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString%>"selectcommand="SELECT TOP 10 ProductID, ProductName FROM Products"></asp:sqldatasource><br /><asp:gridview id="gvProducts" runat="server" datakeynames="ProductID" datasourceid="sdsProducts2"></asp:gridview><asp:sqldatasource id="sdsProducts2" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString%>"onselecting="sdsProducts2_Selecting" selectcommand="SELECT * FROM Products"></asp:sqldatasource>

CODE-BEHIND

protected void sdsProducts2_Selecting(object sender, SqlDataSourceSelectingEventArgs e){if (this.IsPostBack){e.Command.CommandText = String.Format("SELECT * FROM Products WHERE ProductID IN ({0})",this.GetInExpression(lstProducts));}else{e.Cancel =true;}}private string GetInExpression(ListControl control){List<string> list =new List<string>();foreach (ListItem itemin control.Items){if (item.Selected){list.Add(item.Value);}}return String.Join(", ", list.ToArray());}protected void lstProducts_SelectedIndexChanged(object sender, EventArgs e){gvProducts.DataBind();}

|||There must be a more simple way to do this?

No comments:

Post a Comment