I want to pass variable from the code behind to the SelectCommand of a SqlDataSource?
I don\'t want to use built-in parameter types (like ControlParameter, QueryStri
to attach to a GUID:
SqlDataSource1.SelectParameters.Add("userId", System.Data.DbType.Guid, userID);
You need to define a valid type of SelectParameter. This MSDN article describes the various types and how to use them.
SqlDataSource1.SelectCommand = "select * from ta where name like '%'+@p+'%'";
if (SqlDataSource1.SelectParameters.Count == 0)
{
SqlDataSource1.SelectParameters.Add("p", DbType.String, TextBox1.Text);
}
SqlDataSource1.SelectParameters["p"].DefaultValue = TextBox1.Text;
Try this instead, remove the SelectCommand property and SelectParameters:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">
Then in the code behind do this:
SqlDataSource1.SelectParameters.Add("userId", userId.ToString());
SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"
While this worked for me, the following code also works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>
SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());
try with this.
Protected Sub SqlDataSource_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource.Selecting
e.Command.CommandText = "SELECT [ImageID],[ImagePath] FROM [TblImage] where IsActive = 1"
End Sub
You can use the built in OnSelecting parameter of asp:SqlDataSource
Example: [.aspx file]
<asp:SqlDataSource ID="SqldsExample" runat="server"
SelectCommand="SELECT [SomeColumn], [AnotherColumn]
FROM [SomeTable]
WHERE [Dynamic_Variable_Column] = @DynamicVariable"
OnSelecting="SqldsExample_Selecting">
<SelectParameters>
<asp:Parameter Name="DynamicVariable" Type="String"/>
</SelectParameters>
Then in your code behind implement your OnSelecting method: [.aspx.cs]
protected void SqldsExample_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["@DynamicVariable"].Value = (whatever value you want);
}
You can also use this for the other types of DB operations just implement your own methods:
OnInserting="SqldsExample_Inserting"
OnUpdating="SqldsExample_Updating"
OnDeleting="SqldsExample_Deleting"