Reputation: 63
I have a problem where I can't get information from a second form in C#.
I made a easy program to add some names to a ListView
. And somehow I can't get the name from second form.
Form 2:
// this is second form
private String name { get; set; }
private void button1_Click(object sender, EventArgs e)
{
name = textBox1.Text;
this.Close();
}
Form 1:
// and first form on button click AddPerson()
Form2 basicPerson = new Form2();
basicPerson.ShowDialog();
ListViewItem item = new ListViewItem(basicPerson.Name);
listView1.Items.Add(item);
With this code, result I am getting is ListViewItem
with "Form2" name. Does .Close();
somehow kill the Name
variable? How to make this work?
Upvotes: 0
Views: 90
Reputation: 202118
The basicPerson.Name
is not the same as the basicPerson.name
.
C# is case-sensitive.
The basicPerson.Name
is the Control.Name
property (the Form
class descends from the Control
class). And the Control.Name
indeed returns a form name.
Read the basicPerson.name
. Though you better change the property name to avoid future misunderstandings.
And once you switch to name
(or to a better property name), you will find out that you need to change an accessibility level of the property to public
or internal
to be able to read it.
Upvotes: 3
Reputation: 587
Ok, you've got several problems, but nothing complex:
There are some scope keywords in C# which handle weither properties and fields (variables) are visible from outside the class. Those are e.g. public
or private
. To use the advantages of different scopes is an important aspect of object oriented programming. - MSDN Variable and Method Scopes
You've declared a property called name
. It's scope is private
, so you will not be able to call it from outside the Form2
class. If you want to access name
's value, you should change it to public
. If you want to ensure, that name
' value can be read but not changed from outside code, please change the set-accessor
to a private one.
public string PersonName { get; private set; }
Like you have seen, I changed your property's name. This has 2 main reasons:
In C#, property names should be uppercase by code convention. - C# naming convention
Name
is already a property of your Form2
class. This could be disturbing. - MSDN Form class
Last but not least, there's a little typo in your code.
ListViewItem item = new ListViewItem(basicPerson.Name); // <-- "Name" should be "name"
/*---------------------------------------------------------*/
ListViewItem item = new ListViewItem(basicPerson.PersonName); // If you want to use my approach...
Upvotes: 1
Reputation: 26436
The name property is declared private
, which means other classes cannot access it. You should change it to public
or internal
(accessible by other classes within the same project).
Besides that, you're trying to access Name
instead of name
, and C# is case sensitive.
Upvotes: 1