Pages

Search Code Shode

Tuesday, June 15, 2010

How to Pass Query String to User Control : ASP.NET

I have been often asked by people that how to pass query string to user control in ASP.NET.
I decided to solve this problem in this blog post.

In this post I am using example of a Menu Control (used as User Control) which needs to be binded dynamically depending on query string provided to the main page containing user control.

This can be done easily by using public property in the user control.

Following 3 easy steps will help in accomplishing this task!

Step 1:

In your user controls create this property (you can change this according to your situation)

C#

    private string menuId = string.Empty;

    #region Property
    public string MenuID
    {
        set
        {
            menuId = value;
        }
    }

    #endregion


VB.NET

    Private menuId As String = String.Empty

#Region "Property"
    Public WriteOnly Property ChangeMenuID() As String
        Set(value As String)
            menuId = value
        End Set
    End Property

#End Region


Step 2:
Set Menu ID property of your user control from parent page like:

C#


YourUserControlID.MenuID = Request.QueryString["menuid"].ToString();// or from any other variable
YourUserControlID.BindMenuData();

VB.NET

YourUserControlID.MenuID = Request.QueryString("menuid").ToString() ' or from any other variable
YourUserControlID.BindMenuData()


Step 3:
Write this function in your user control which will bing the Menu from database depending on query string provided to the parent page having user control.

C#

    // This function is to be written in the user control
    public void BindMenuData()
    {
        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.CommandText = "select * from [YourTableName] Where MenuID = @MenuID";
        sqlCmd.Parameters.AddWithValue("@MenuID", menuId);
        sqlCmd.CommandType = CommandType.Text;

        SqlConnection sqlCOn = new SqlConnection("Connection String.. bla bla");
        sqlCOn.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd);
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        sqlCOn.Close();
        Menu1.DataSource = ds;
        Menu1.DataBind();
    } 


VB.NET

    'This function is to be written in the user control
    Public Sub BindMenuData()
        Dim sqlCmd As New SqlCommand()
        sqlCmd.CommandText = "select * from [YourTableName] Where MenuID = @MenuID"
        sqlCmd.Parameters.AddWithValue("@MenuID", menuId)
        sqlCmd.CommandType = CommandType.Text

        Dim sqlCOn As New SqlConnection("Connection String.. bla bla")
        sqlCOn.Open()
        Dim adapter As New SqlDataAdapter(sqlCmd)
        Dim ds As New DataSet()
        adapter.Fill(ds)
        sqlCOn.Close()
        Menu1.DataSource = ds
        Menu1.DataBind()
    End Sub



That's That! ;)

Still have confusion ??
Feel free to ask!

اشتہارات