Creating Custom Parameters for Data source Controls
Asp.net provide various types of parameters , like session parameter which get its value from session ,control parameter which get its value from form control , and there is also many other parameters each one used to read the parameter value from different location .
But sometimes , those parameters doesn't fit your needs , for example , if you want a parameter that get its value from the UserName of the current logged in user ( User.Identity.Name ) , in this case you may end up by using the default <asp:Parameter > which requires to set its value manually in the data Source Selecting , Updating , Inserting , or deleting event.
However , you could create a custom parameter that can be used in all places that you want to use the Current logged in UserName as a parameter in the data source controls , this can be accomplished by inheriting from System.Web.UI.WebControls.Parameter class , and by overriding it's Evaluate method.
Note: the evaluate method will be called automatically by the framework .
The custom parameter can be placed in App_Code folder or in a separate class library if you want to use it in other projects.
This is the custom UserParameter class:
11 namespace CustomControls
12 {
13 /// <summary>
14 /// Summary description for UserParameter
15 /// </summary>
16 public class UserParameter : System.Web.UI.WebControls.Parameter
17 {
18 protected override object Evaluate(HttpContext context, System.Web.UI.Control control)
19 {
20 if (context.User != null && !string.IsNullOrEmpty(context.User.Identity.Name))
21 {
22 return context.User.Identity.Name;
23 }
24
25 return null;
26 }
27 }
28 }
Now to use the UserName parameter,
First thing , you should register the custom control ,
<%@ Register Namespace="CustomControls" TagPrefix="cc1" %>
Then you can use it as a parameter for your data source :
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<$ConnectionStrings:DatabaseConnectionString %>"
SelectCommand="SELECT [ProjectId], [Name], [UserName] FROM [Projects] where [UserName]=@UserName">
<SelectParameters>
<cc1:UserParameter Name="UserName" />
</SelectParameters>
</asp:SqlDataSource>
Hope it helps
Anas Ghanem