Hello everyone,
I am working on a project that when a user select an item in the listbox data will display in the textboxes. I saw a thread named "Experiment with ListBox in C#", this thread does cover what I am trying to implement on my project. I copied and pasted that code into Visual C# 2008 and it does not fire. That is the problem I have been having ever since the school project. The school project was submitted for grading already done deal. LOL

School project:
This is an address book with arrays. single dimension.
firstname, lastname, address, city, state, zip
Six textboxes, listbox, add btn, deletebtn, exitbtn.

The user is to enter data into textboxes, display only names to listbox sorted in alphabetical order

The user select a name in listbox, display address information to textbox.

I am having the problem that when I select a name to display addresses to the textbox it does nothing to display.

//this suppose to fire when user select an item in listbox to textbox
//I think this is where i am having the problem
private void lstNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            //  Displays address into the text boxes. 

            //  Sets the array count variable makes sure index is not -1.

            if (lstNames.SelectedIndex > 0)
            {
                
                string arrayName;
                arrayName = lstNames.SelectedItem.ToString();

                //  Loop through the arrayString to display the address of each person.

                for (int index = 0; index > 20; index++)
                {

                   if (lstNames.ToString() == arrayName)
                    {
                        //  if names match then set the text box text to the array location elements.

                        txtlastname.Text = arrayString[0];
                        txtfirstname.Text = arrayString[1];
                        txtAddress.Text = arrayString[2];
                        txtCity.Text = arrayString[3];
                        txtState.Text = arrayString[4];
                        txtZip.Text = arrayString[5];

                    }
                    else
                    {
                            //did not find the data show the error messagebox

                            MessageBox.Show("Address not found!", "Data Error Entry",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);

                        }
                       
                    }
                }


            }
//this is my class-level 
public partial class Form1 : Form
    {
        public int Counter = 0;

        //declaring array with 20 elements
        public string[] arrayString = new string[20];

        public Form1()
        {
            InitializeComponent();

        }
//my add button with stored array store up to 20 entries
//I can add entries without a problem
//also clears textbox for next entry and sort alphabetical order
//no problem with this
private void btnAdd_Click(object sender, EventArgs e)
        {
            //execute the counter as incrementor
            Counter++;
            //declare variable as integer
            int arrayCounter;
            //compare the counter less than 20
            if (Counter <= 20)
            {
                //then arrayCounter will either add or equal to 1
                arrayCounter = Counter += 1;
                //initializing and store array to display to textbox
                arrayString[0] = txtlastname.Text;
                arrayString[1] = txtfirstname.Text;
                arrayString[2] = txtAddress.Text;
                arrayString[3] = txtCity.Text;
                arrayString[4] = txtState.Text;
                arrayString[5] = txtZip.Text;

                //add a list of names by lastname with separator as format
                lstNames.Items.Add(arrayString[0] + ", " + arrayString[1]);
                //alphabetical order
                lstNames.Sorted = true;
                //string empty and brings back the focus to lastname textbox
                //making room for more information
                txtfirstname.Text = String.Empty;
                txtlastname.Text = String.Empty;
                txtAddress.Text = String.Empty;
                txtCity.Text = String.Empty;
                txtState.Text = String.Empty;
                txtZip.Text = String.Empty;
                txtfirstname.Focus();

            }
            else
            {
                //otherwise an error messagebox will appear 
                //alerting the user that only 20 entries are permitted
                MessageBox.Show("You've reached 20 Addresses...permitted", "Error");
            }
        }
//this delete entry from the listbox when user select an item
//no problem is does delete an entry in listbox
private void btnDelete_Click(object sender, EventArgs e)
        {
            //decision to delete a record from listbox
            if (lstNames.SelectedIndex > -1)
            {
                lstNames.Items.RemoveAt(lstNames.SelectedIndex);

            }
        }

I have been working on this project for over a week.
This is the introduction to C# class, not an advanced class.
But I am also curious, if the I enter data in the textboxes and click on add the names will only show in the listbox, but then since this is an array it suppose to be stored in the array memory, so when I select a name in the listbox the addresses suppose to display in the textboxes?

I greatly appreciate for your assistance, I really need to learn this.
Thanks!

Regards,

Desi Bravo

Hi bravo659!
Glad you came back with your code.
2 things to start with :
--> Line 17 of your SelectedIndexChanged code reads :
for (int index = 0; index > 20; index++)
change it to this if you ever want to enter the for loop:
for (int index = 0; index < 20; index++)

--> Line 20: lstNames.ToString() will give you the default string of a listbox object which is something like : "System.Windows.Forms.ListBox, Items.Count: 3, Items[0]: firstitemstr" and probably not what you want.

Comments:

In your btnAdd_Click event:

private void btnAdd_Click(object sender, EventArgs e)
        {
            //execute the counter as incrementor
            Counter++;
            //declare variable as integer
            int arrayCounter;
            //compare the counter less than 20
            if (Counter <= 20)
            {
                //then arrayCounter will either add or equal to 1
                arrayCounter = Counter += 1;

1) You never use "arrayCounter".
2) You are adding 1 to Counter ( Counter += 1 ) before assigning it to arrayCounter, which means you have now added 2 to Counter since you entered this method

In line 20 of lstNames_SelectedIndexChanged , you are comparing apples to oranges, if (lstNames.ToString() == arrayName) , because the ListBox.ToString() will return something like "System.Windows.Forms.ListBox", and not the item of the ListBox. I believe you want to compare to your arrayString array, but you will never find the entry since you concatenated lastname with firstname before adding the item to the listbox, so the strings will never match in a compare unless reconstruct the concatenation for comparison...

Your array (arrayString) will hold 20 strings, but not 20 entries containing the following data for each entry:

Lastname
Firstname
Address
City
State
Zip

In order to accomplish this with your array approach, you need to make it two dimensional: string [,] arrayString = new string[20,7]; for example.

Well, that is a quite a bit to fix already. Start with that two dimensional array. I and others are dying to show you an alternative (List<>), but you need to get a grasp on multi-dimension arrays.

Open the Form1.designer.cs file and check for this line: this.lstNames.SelectedIndexChanged += new System.EventHandler(this.lstNames_SelectedIndexChanged); This is the line that tells the compiler what method to fire when the event is raised.

You can create this event handler in several ways:
1) Add it manually in the the form constructor method:

public Form1()
        {
            InitializeComponent();
            this.lstNames.SelectedIndexChanged+=new EventHandler(lstNames_SelectedIndexChanged);
        }

2) use the visual studio designer to add it automatically to the form1.designer.cs code by a) doubleclicking on the listbox, or b) clicking the lightning bolt symbol at the top of the properties window and then double clicking the box next to the relevent event.

3) add the above line to the designer.cs file manually. I'm not sure on the principle here. I do this from time to time, but the code in that file is supposed to be autogenerated by the designer so it may be bad practice to change it : /

Sorry I didn't answer your original question, but Ryshad covered it. As I was looking through the code, I began finding areas of concern and that is what I noted--then forgot to mention checking that the event handler was being added...:(

Comments:

In your btnAdd_Click event:

private void btnAdd_Click(object sender, EventArgs e)
        {
            //execute the counter as incrementor
            Counter++;
            //declare variable as integer
            int arrayCounter;
            //compare the counter less than 20
            if (Counter <= 20)
            {
                //then arrayCounter will either add or equal to 1
                arrayCounter = Counter += 1;

1) You never use "arrayCounter".
2) You are adding 1 to Counter ( Counter += 1 ) before assigning it to arrayCounter, which means you have now added 2 to Counter since you entered this method

In line 20 of lstNames_SelectedIndexChanged , you are comparing apples to oranges, if (lstNames.ToString() == arrayName) , because the ListBox.ToString() will return something like "System.Windows.Forms.ListBox", and not the item of the ListBox. I believe you want to compare to your arrayString array, but you will never find the entry since you concatenated lastname with firstname before adding the item to the listbox, so the strings will never match in a compare unless reconstruct the concatenation for comparison...

Your array (arrayString) will hold 20 strings, but not 20 entries containing the following data for each entry:

Lastname
Firstname
Address
City
State
Zip

In order to accomplish this with your array approach, you need to make it two dimensional: string [,] arrayString = new string[20,7]; for example.

Well, that is a quite a bit to fix already. Start with that two dimensional array. I and others are dying to show you an alternative (List<>), but you need to get a grasp on multi-dimension arrays.

Hi DdoubleD,
Thanks, I apprecate your feedback.
Yes, it is quite some fix I have to make. Ok, I will do that and get back in here with the results. Thanks.

Regards,

Desi

LOL, thats ok I have to do a few things of you mentioned and what Ryshad also mentioned so I can get it to work.

I will definitely check on that and will add it to the constructor.
Thanks Ryshad.
I do need to get a grasp on this.

@bravo659 no problem, the best way to deal with control events is to use the events tab (lightning bolt) in the properties window. You can see a full list of events and create handlers just by double clicking in the box :)

@DdoubleD dont kick yourself, you spotted errors that need fixing...i saw some posts from bravo in other threads so i was pretty sure of the root of the problem already :p

Hello Ryshad,
Yes I see it, already included:

this.lstNames.SelectedIndexChanged += new System.EventHandler(this.lstNames_SelectedIndexChanged);

Hi DdoubleD,
Thanks, I apprecate your feedback.
Yes, it is quite some fix I have to make. Ok, I will do that and get back in here with the results. Thanks.

Regards,

Desi

Hello ddoubled,
I made a few changes.

This is where I changed the array to two-dimensional

public partial class Form1 : Form
    {
        public int Counter = 0;

        //declaring array with 20 elements
        public string[,] arrayString = new string[20,7];

        public Form1()
        {
            InitializeComponent();

        }

This is the btnAdd event

private void btnAdd_Click(object sender, EventArgs e)
        {
            //execute the counter as incrementor
            Counter++;
            //declare variable as integer
            
            //compare the counter less than 20
            if (Counter <= 20)
            {
                //then arrayCounter will either add or equal to 1
                 Counter += 1;
                //initializing and store array to display to textbox
                arrayString[0,0] = txtlastname.Text;
                arrayString[0,1] = txtfirstname.Text;
                arrayString[0,2] = txtAddress.Text;
                arrayString[0,3] = txtCity.Text;
                arrayString[0,4] = txtState.Text;
                arrayString[0,5] = txtZip.Text;

                //add a list of names by lastname with separator as format
                lstNames.Items.Add(arrayString[0,1] + ", " + arrayString[1,0]);
                //alphabetical order
                lstNames.Sorted = true;
                //string empty and brings back the focus to lastname textbox
                //making room for more information
                txtfirstname.Text = String.Empty;
                txtlastname.Text = String.Empty;
                txtAddress.Text = String.Empty;
                txtCity.Text = String.Empty;
                txtState.Text = String.Empty;
                txtZip.Text = String.Empty;
                txtfirstname.Focus();

            }
            else
            {
                //otherwise an error messagebox will appear 
                //alerting the user that only 20 entries are permitted
                MessageBox.Show("You've reached 20 Addresses...permitted", "Error");
            }
        }

This is the selectedindexchanged event

private void lstNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            //  Displays address into the text boxes. 

            //  Sets the array count variable makes sure index is not -1.

            if (lstNames.SelectedIndex > 0)
            {
                
                //string arrayName;
                //arrayName = lstNames.SelectedItem.ToString();

                //  Loop through the arrayString to display the address of each person.

                for (int index = 0; index < 20; index++)
                {

                   if (lstNames.ToString() == arrayString.ToString())
                    {
                        //  if names match then set the text box text to the array location elements.

                        txtlastname.Text = arrayString[0,2];
                        txtfirstname.Text = arrayString[0,1];
                        txtAddress.Text = arrayString[0,3];
                        txtCity.Text = arrayString[0,4];
                        txtState.Text = arrayString[0,5];
                        txtZip.Text = arrayString[0,6];

                    }
                    else
                    {
                            //did not find the data show the error messagebox

                            MessageBox.Show("Address not found!", "Data Error Entry",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);

                        }
                       
                    }
                }

Here's an idea, let's focus on the btnAdd for now...

When you are populating your array, you are always overwriting the first person with arrayString[0,n] because coord zero is always the first person.

I'm pretty sure you want to use your Counter as the index in the above, but you shouldn't be incrementing before and after the if statement: if (Counter <= 20) , which also has a problem if you use it as the index because if it equals 20, you will blow (out of range) the allocated string array's size...

Fix those and come back--okay?..

Suggestion: google "arrays c# tutorial" and browse some tutorials and examples. Sometimes the textbook doesn't always "sink in" and additional references is all it takes for that to happen. Not to brag at all, but I could easily fix the areas above, but that wouldn't benefit either one of us. Use the web as your main resource, then when you get stuck with something particular, let us know because we do want to help.

aye, DdoubleD is right, get the items adding correctly, then work on retrieving them. If you cant be sure of the data your working with its very hard to tell why things arent working :)

As well as what she has pointed out regarding the counter and index issues, you have entered the names as lstNames.Items.Add(arrayString[0,1] + ", " + arrayString[1,0]); which is the first name of person 1 and the last name of person 2. I think you need to read around the subject as DdoubleD suggested, working with arrays requires a good grasp of how they work.

The first thing to understand is the indexing. In C# arrays and collections are zero-based. That means that the first item is at index 0, not 1. So if you have an array of 20 items they will be indexed (numbered) from 0 to 19.

Whilst a single dimension array is like a list, it might help to imagine a 2D array as a table. so for your example you have a table with 7 columns (numbered from 0 to 6) and 20 rows (numbered 0 to 19).

Ive shown the table here (i dropped the last column as you werent using it and i couldnt fit it in the box):

lName	fName	address	city	state	zip
	0	1	2	3	4	5
0	smith	ted	12 Ab St	Aville	AB	12345
1	jones	paul	34 Ab Rd	Btown	BC	67890
2						
3						
...						
19

So to get/set the third persons First Name you would reference array index [2,1] or the 20th persons city would be [19,3].
To get all the info for the 8th person you would need [7,0] through to [7,5].

Hope that helps settle things in your mind. Once you get a handle on the indexing they are much easier to work with.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.