Friday, March 20, 2009

Postcode Finder - Using ListBox and Textbox


The specs of this program are as follows:
  • one string array that will contain the names of suburbs
  • one int array that will contain the list of postcode
  • one listbox, one dropdown
First things first, we need to create the two arrays. We might want to declare and initialise both of them in the class section as we want both arrays to have visibility (I prefer the term Scope) throughout the whole program.

string[] sSuburb = { "Ashfield", "Balmain", "Circular Quay", "Newtown", "Petersham", "Redfern" };
string[] sPostcode = { "2131", "2041", "2000", "2042", "2049", "2016" };


Now, we need to bind the suburb and postcode arrays to the dropdown and the listbox respectively. We might want add them one by one, but as Allan said, when you see ARRAYS, YOU USE FOR LOOPS :D

As a consequence, the for loop as shown below will loop from i=0 because any array whatsoever starts with element 0.
The condition for this loop is that it should not exceed the length of the array, hence we use the array property Array.Length.
We use the control.Items.Add because we want them to be added dynamically (at runtime, not at design time). We can use only one for loop to populate both controls:

for (int i = 0; i < sSuburb.Length; i++)
{
cboSuburb.Items.Add(sSuburb[i]);
lisPostCode.Items.Add(sPostcode[i]);
}

Done! Now, we try to make the the association between suburb name and postcode. Let's say, we want to make the postcode in the listbox to change when we choose any suburb from the dropdown.
We need to make the change in suburb dropdown because the dropdown change will trigger the change in the listbox, yes?

private void cboSuburb_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = cboSuburb.SelectedIndex;
//change list
lisPostCode.Text = sPostcode[iIndex];
}

The iIndex variable will just store the index of the suburb that is changed. You could also write the following, by omitting the iIndex variable:

lisPostCode.Text = sPostcode[cboSuburb.SelectedIndex];


but it affects readability, so we try to avoid this.


We do the same for the listbox, as follows:

private void lisPostCode_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = lisPostCode.SelectedIndex;
//change list
cboSuburb.Text = sSuburb[iIndex];
}


Click Build, run and enjoy. Easy right? :D

No comments:

Post a Comment