.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Making an Adapter

Posted By:Shashi Ray       Posted Date: February 23, 2009    Points: 15    Category: C#    URL: http://www.dotnetspark.com  
 

Making an Adapter

 

Now it is a little awkward to remember to use the Items collection of the list box for some operations and not for others. For this reason, we might prefer to have a class that hides some of these complexities and adapts the interface to the simpler one we wish we had, rather like the list box interface in VB6. We'll create a simpler interface in a ListAdapter class which then operates on an instance of the ListBox class:

 

public class ListAdapter {

private ListBox listbox; //operates on this one

public ListAdapter(ListBox lb) {

listbox = lb;

}

//-----

public void Add(string s) {

listbox.Items.Add (s);

}

//-----

public int SelectedIndex() {

return listbox.SelectedIndex;

}

//-----

public void Clear() {

listbox.Items.Clear ();

}

//-----

public void clearSelection() {

int i = SelectedIndex();

if(i >= 0) {

listbox.SelectedIndex =-1;

}

}

}

 

Then we can make our program a little simpler:

 

private void btClone_Click(object sender, EventArgs e) {

int i = lskids.SelectedIndex ();

if( i >= 0) {

Swimmer sw = swdata.getSwimmer (i);

lsnewKids.Add (sw.getName() + "\t" + sw.getTime ());

lskids.clearSelection ();

}

}

 

Now, let's recognize that if we are always adding swimmers and times space apart like this, maybe there should be a method in our ListAdapter that handles the Swimmer object directly:

 

public void Add(Swimmer sw) {

listbox.Items.Add (sw.getName() + "\t" + sw.getTime());

}

This simplifies the click event handler even more:

private void btClone_Click(object sender, EventArgs e) {

int i = lskids.SelectedIndex ();

if( i >= 0) {

Swimmer sw = swdata.getSwimmer (i);

lsnewKids.Add (sw);

lskids.clearSelection ();

}

}

 

 

Shashi Ray


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend