Reputation: 14161
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();
}
}
}
Upvotes: 0
Views: 443
Reputation: 9861
C# has superseded the Observer pattern, it has events; events are a language level implementation of the Observer pattern. What you want to do is create an event on your object and then make your observers subscribe to it.
Upvotes: 1
Reputation: 5293
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();
}
Upvotes: 1