0

I am trying to pass a string that is in a listbox to another form when it is double clicked. I have done this without issue multiple times in the past. However, on the second form when it is launched the string is blank.

Code:

Form passing string (Form5):

private void listBoxCurrentRentals_DoubleClick(object sender, EventArgs e)
    {
        selectedGame = listBoxCurrentRentals.SelectedItem.ToString();
        Form17 reviewForm = new Form17();
        reviewForm.Show();
    }

Recieving form (Form17): game string is declared at the start of the code.

game = Form5.selectedGame;
textBoxGame.Text = game;

Thanks

DerStarkeBaer
  • 669
  • 8
  • 28
Tim7345
  • 19
  • 1
  • 7
  • What you describe is an “awkward” way to pass the value from `Form5` to `Form17`. The only way I can see it working is if the variable `selectedGame` in `Form5` is a “static” variable AND `Form5` has been instantiated. If you are getting an error on the line: `game = Form5.selectedGame;` … that says … _“An object reference is required for the non-static field, … selectedGame”_ … then, making `selectedGame` in `Form5` a `static` variable should fix this. – JohnG Jun 24 '20 at 08:07
  • 1
    However, this is not the correct/proper way to pass values between forms. There are many ways to do this and I suggest some research on passing values between forms. One of the easiest ways to accomplish this is to literally “pass” the value to the form like… `Form17 reviewForm = new Form17(selectedGame);` … then create a `Form17` constructor that takes the passed in string… something like… `public Form17(string selectedGame) { InitializeComponent(); textBoxGame.Text = selectedGame; }` – JohnG Jun 24 '20 at 08:07
  • 1
    I found the issue, I had set the textbox to fill when a button had been clicked, not when the form initially loaded. Thanks for the help everyone – Tim7345 Jun 24 '20 at 08:49

2 Answers2

0

In the Form17 add a property to store value of the selected game (setter):

public string SelectedGame
{ 
   set; 
   private get;
}

In the Form5 in the method which handle the double click event, before to execute Show() reviewForm method, set the value of the selected game:

private void listBoxCurrentRentals_DoubleClick(object sender, EventArgs e)
    {
        Form17 reviewForm = new Form17();
        reviewForm.SelectedGame = listBoxCurrentRentals.SelectedItem.ToString();
        reviewForm.Show();
    }
0

Another way is to use constructor

private void listBoxCurrentRentals_DoubleClick(object sender, EventArgs e)
    {
        selectedGame = listBoxCurrentRentals.SelectedItem.ToString();
        Form17 reviewForm = new Form17(selectedGame);
        reviewForm.Show();
    }



public class Form17
{
  string someValue;
  public Form17(string someValue)
  {
   this.someValue=someValue;
  }
}
Naveed Yousaf
  • 436
  • 4
  • 14