C# - Using Delegate Function

microkarl

Regular
Joined
Apr 22, 2004
Messages
88
Location
Morristown, NJ
All, I am a VB.NET programmer so please excuse me if the question is kinda dumb. I have a Web Service and a web page to call and retrieve data from the web serivce and pop them into a datagrid, the code is as follow:

Code:
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        Dim objWS As New NorthWindWS.Products
        Try
            If Not Page.IsPostBack Then
                objWS.BeginRetrieveAllProducts(New AsyncCallback(AddressOf RetrieveData_CallBack), objWS)
            Else
                lblError.Visible = False
                lblError.Text = String.Empty
            End If
        Catch ex As Exception
            lblError.Visible = True
            lblError.Text = ex.ToString
        End Try
    End Sub

    Private Sub RetrieveData_CallBack(ByVal ar As System.IAsyncResult)

        Dim dsTemp As New DataSet
        Dim ws As NorthWindWS.Products = CType(ar.AsyncState, NorthWindWS.Products)
        dsTemp = ws.EndRetrieveAllProducts(ar)

        With dgProducts
            .DataSource = dsTemp.Tables(0)
            .DataBind()
        End With

    End Sub

End Class

If I have to do the exact same thing in C#, how to do it? I know C# is more strict on using delegates and need to declare the delegate functions first before using... can anyone help!

Thanks,
Carl
 
Something like
C#:
        private void Page_Load(object sender, EventArgs e)
        {

            NorthWindWS.Products objWS = new NorthWindWS.Products();
            try
            {
                if (!Page.IsPostBack)
                    objWS.BeginRetrieveAllProducts(new AsyncCallback(RetrieveData_CallBack), objWS);
                else
                {
                    lblError.Visible = False;
                    lblError.Text = String.Empty;
                }
            }
            catch (Exception exception)
            {
                lblError.Visible = true;
                lblError.Text = ex.ToString();
            }

        }

        private void RetrieveData_CallBack(IAsyncResult ar)
        {
            DataSet dsTemp = new DataSet();
            NorthWindWS.Products ws = (NorthWindWS.Products)ar.AsyncState;
            dsTemp = ws.EndRetrieveAllProducts(ar);

            dgProducts.DataSource = dsTemp.Tables(0);
            dgProducts.DataBind();
        }
should do the trick.
 
You must also include Async="true" in your Page directive:

<%@ Page Async="true" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
Back
Top