Updating Listbox in Another Form

photo123

Member
Joined
Feb 11, 2020
Messages
18
Programming Experience
Beginner
I have 2 forms. Form1 contains a list box and a button that says update. If the user selects a number from the list box and clicks the update button then form2 pops up. Then the user can enter a number in form2 and click the update button. I want the number that the use enters to be updated in the list box. For example: form1 list box contains 1,2,3. If the user decides they want to change the number 2, they select it and click update button. When form2 pop's up the user enters the number 90 instead of 2. Finally when they click update I want the listbox in form1 to update to 90 (still keeping the other numbers).

C#:
//FORM 1 CODE
private void btnUpdate_Click(object sender, EventArgs e)
        {
            Form UpdateScore = new UpdateScore();
            DialogResult update = UpdateScore.ShowDialog();

            if (update == DialogResult.OK)
            {
                for (listBox1.SelectedItem.Item)
                {
                    listbox1.Items.Add(txtScore.Tag);
                }
              
            }
              
        }

C#:
//FORM 2 CODE
private void btnUpdate_Click(object sender, EventArgs e)
        {
            this.Tag = txtScore.Text;
            this.DialogResult = DialogResult.OK;

        }

This is what I have so far but I'm getting errors in my for loop that I'm not sure how to fix. I don't understand why I'm getting errors for my selected item in my for loop because when I looked it up thats what I found for listbox selections. Can someone please help me out? Thanks.
 
You should be exposing the number that the user entered in the second form via a property in that form. The first form then simply gets that property value and updates its own ListBox. How do you ALWAYS get data into and out of an object? You either get/set a property or you call a method. Why should this be any different? Declare either a read-only property or a method that returns the data entered by the user and then use that property or method the same way you have a hundred times before.
 
The OP is using the Win32 API / .NET Framework 1.1 approach of using the Tag property of Form2 to expose the value that the user entered. As @jmcilhinney recommends, it's better to use an explicitly name property to expose this.

As for the mechanics of replacing the value once you get it back, the OP needs to replace his current code that looks like:
C#:
if (update == DialogResult.OK)
{
    for (listBox1.SelectedItem.Item)
    {
        listbox1.Items.Add(txtScore.Tag);
    }
}
with code that replaces, not adds, the currently selected item.
 
Back
Top Bottom