Search code examples
c#.net.net-2.0c#-2.0asp.net-2.0

Implementing Observer Pattern to execute a method in a class


I am using c# [ASP.NET 2.0 - VS 2005] and I want to implement Observer Pattern to fire a method (residing in a class) as and when DropDown index changes. There are three DropDowns and a Label Control which should display newly generated scheme code in real-time, as and when DropDown index changes.

public sealed class GetSchemeCode:INotifyPropertyChanged
{

    private string _distCode;
    private string _blockCode;
    private string _schmType;


    public string DistCode
    {
        get { return _distCode; }
        set { _distCode = value; }
    }
    public string BlockCode
    {
        get { return _blockCode; }
        set { _blockCode = value; }
    }
    public string SchemeType
    {
        get { return _schmType; }
        set { _schmType = value; }
    }


    public GetSchemeCode()
    {
        //
        // TODO: Add constructor logic here
        //
    }


    protected string GetNewSchemeCode()
    {
        SqlCommand cmdSchmCode = new SqlCommand("GenerateSchemeCode", dbConnection.cn);
        try
        {
            cmdSchmCode.CommandType = System.Data.CommandType.StoredProcedure;
            //Add Parameters
            cmdSchmCode.Parameters.AddWithValue("@districtCode", DistCode.ToString());
            cmdSchmCode.Parameters.AddWithValue("@blockCode", BlockCode.ToString());
            cmdSchmCode.Parameters.AddWithValue("@schemeType", SchemeType.ToString());
            dbConnection.OpenConnection("Scheme");
            return cmdSchmCode.ExecuteScalar();
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            cmdSchmCode.Dispose();
            dbConnection.CloseConnection();
        }
    }

}

Solution

  • Do something like the code below to hook up the Dropdown list's selected index changed property. That is Asp.Net's implementation of the Observer pattern behind the scenes I believe. You can set the AutoPostBack property and the Event hookup either in code or in the html markup.

    public GetSchemeCode()
    {
            DistCodeDropDownList.AutoPostBack = true;
            DistCodeDropDownList.SelectedIndexChanged += new EventHandler(DistCodeDropDownList_SelectedIndexChanged);
    
            // TODO: Hook up the other DropDownLists here. as well
    }
    
        void DistCodeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            CodeOutputLabel.Text = GetNewSchemeCode();
        }