mohammed abd elgwad
mohammed abd elgwad

Reputation: 135

Passing string between two forms

I have a problem in passing a string value between two forms.

First I created public string sanacode which I assign the value passed in form 2

Form 1 code

AnalysisEdit ae = new AnalysisEdit();
int Row = dataGridView1.CurrentRow.Index;
ae.sanacode = dataGridView1[0, Row].Value.ToString();
ae.Show();

Form 2 constructor code

public AnalysisEdit()
{
    InitializeComponent();
    MessageBox.Show(sanacode,);
}

it shows me nothing

Upvotes: 0

Views: 787

Answers (5)

venerik
venerik

Reputation: 5904

You could temporarily add MessageBox.Show() to your setter:

// In Form2
public sanacode
{
  set
  {
    _sanacode = value;
    MessageBox.Show(_sanacode);
  }

  get
  {
    return _sanacode;
  }
}

Upvotes: -1

Bonnie DeWitt
Bonnie DeWitt

Reputation: 1

Perhaps you'd like some ideas for the various ways to pass data between forms. I have written two blog posts on the subject:

http://geek-goddess-bonnie.blogspot.com/2011/01/passing-data-between-forms.html

http://geek-goddess-bonnie.blogspot.com/2012/12/passing-data-between-forms-redux_31.html

Upvotes: 0

Kristian Fenn
Kristian Fenn

Reputation: 867

The issue is that you're not calling things in the correct order. The form 2 constructor code will be called on line 1 of the form code, or AnalysisEdit ae = new AnalysisEdit(); However, this is before the assignment that takes place on line 3: ae.sanacode = dataGridView1[0, Row].Value.ToString(); So when you show the messagebox in the form 2 constructor, sanacode has not yet been assigned to.

There are two ways to fix this. Firstly, you can pass the value in via the constructor as per @kostas ch.'s answer, or you can override the form's OnShown event in form 2:

protected override void OnShown(EventArgs e)
{
    MessageBox.Show(sanacode);
}

Upvotes: 1

Shamshiel
Shamshiel

Reputation: 2211

I wouldn't put your code

MessageBox.Show(sanacode,);

in the constructor. I would use the "Load"-Event. If you use the "Load"-Event your MessageBox will Show, when you use

ae.Show();

Like this

private void AnalysisEdit_Load(object sender, EventArgs e)
    {
        MessageBox.Show(sanacode);
    }

Upvotes: 0

kostas ch.
kostas ch.

Reputation: 2035

Change you constructor from

public AnalysisEdit()
{
   InitializeComponent();
   MessageBox.Show(sanacode);
}

to

public AnalysisEdit(string sanacode)
{
    InitializeComponent();
    MessageBox.Show(sanacode);
}

form call

int Row = dataGridView1.CurrentRow.Index;
AnalysisEdit ae = new AnalysisEdit(dataGridView1[0, Row].Value.ToString());    
ae.Show();

Upvotes: 2

Related Questions