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
I love Al W's answer. There's a typo though.
<asp:DelegateParameter Name="userId" DbType="Guid" OnEvaluate="GetUserID" />
--- Should be ---
<asp:DelegateParameter Name="userId" DbType="Guid" OnEvaluateParameter="GetUserID" />
Hopefully, this saves someone a few minutes.
we had to do this so often that I made what I called a DelegateParameter class
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Reflection;
namespace MyControls
{
public delegate object EvaluateParameterEventHandler(object sender, EventArgs e);
public class DelegateParameter : Parameter
{
private System.Web.UI.Control _parent;
public System.Web.UI.Control Parent
{
get { return _parent; }
set { _parent = value; }
}
private event EvaluateParameterEventHandler _evaluateParameter;
public event EvaluateParameterEventHandler EvaluateParameter
{
add { _evaluateParameter += value; }
remove { _evaluateParameter -= value; }
}
protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control)
{
return _evaluateParameter(this, EventArgs.Empty);
}
}
}
put this class either in your app_code (remove the namespace if you put it there) or in your custom control assembly. After the control is registered in the web.config you should be able to do this
<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">
<SelectParameters>
<asp:DelegateParameter Name="userId" DbType="Guid" OnEvaluate="GetUserID" />
</SelectParameters>
</asp:SqlDataSource>
then in the code behind you implement the GetUserID anyway you like.
protected object GetUserID(object sender, EventArgs e)
{
return userId;
}
See if it works if you just remove the DbType="Guid" from the markup.
Just add a custom property to the page which will return the variable of your choice. You can then use the built-in "control" parameter type.
In the code behind, add:
Dim MyVariable as Long
ReadOnly Property MyCustomProperty As Long
Get
Return MyVariable
End Get
End Property
In the select parameters section add:
<asp:ControlParameter ControlID="__Page" Name="MyParameter"
PropertyName="MyCustomProperty" Type="Int32" />