cyboashu
cyboashu

Reputation: 10433

C# unable to understand how static property works

I am a novice to C# language. I have created a user form and added a listview (chnaged it to public) on it. Now I have added a static classlike this

public static class listView
    {
        private static ListView.ListViewItemCollection litm;
        public static ListView.ListViewItemCollection listItems
        {

            get
            {
                Form1 frm = new Form1();
                return frm.listView1.Items;
            }

            set
            {
                litm = value;
            }
        }
    }

Now added following code behind a button ,

 private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(listView.listItems.Count.ToString()); //Works
            listView.listItems.Add("Fail"); //Fails
            this.listView1.Items.Add("HH"); //Works
        }

Here, I am able to use get the count of items. I think get works. But when I am trying to add a new item, it does nothing. No error but no entry is added.

I am interested to learn why that's happening. Any guidance is appreciated.

Upvotes: 2

Views: 160

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125187

In your getter for property, you are creating a new instance of form 1 and add item to that.

It is not related to being static or non-static.

Look at this:

get
{
    Form1 frm = new Form1();
    return frm.listView1.Items;
}

So when you

listView.listItems.Add("Fail");

you are adding item to list view of form 1 that you can't see it.

Infact every time you access listView.listItems property, you are creating a newinstance of form 1 and adding an item to its listview1.

But in this line:

this.listView1.Items.Add("HH");

you are adding the item to the list view that you are seeing.

To learn about static:

Upvotes: 2

Related Questions