priyank bhardwaj
priyank bhardwaj

Reputation: 119

DataGridView Showing Empty Rows when assigned to a List of Type containing internal properties

I experienced an issue which kind of opposed my basic C# concepts on Access Modifiers. So i build a Sample application reproducing Same Scenario.

There is a Parent Form with Click Button on the event of which a new Form spawns with a DataGridView. The Data Source is static string,string and the properties are internal as i am using everything in the same project.

To my surprise, there were 5 rows made since i had 5 data items bind to that grid but were just empty Rows. Then i made the properties as public and i was able to get them. All the Rows were populated with correct Data the second Time.

Parent Form

namespace SampleApp{
public partial class Form1 : Form
{
    List<ItemModel> modelList = new List<ItemModel>();

    public Form1()
    {
        InitializeComponent();
    }

    private void btnClick_Click(object sender, EventArgs e)
    {
        LoadData();
        using (SeperateWindow window = new SeperateWindow(modelList))
        {
            window.PopulateGrid();
            if(window.ShowDialog() == DialogResult.OK)
            {

            }
        }
    }

    public void LoadData()
    {
        for(int i= 0; i < 5; i++)
        {
            ItemModel item = new ItemModel($"Name { i}", i.ToString());
            modelList.Add(item);
        }
    }
}

Model Class

namespace SampleApp.Model{
sealed class ItemModel
{
    internal string Textvalue { get; set; }
    internal string ID { get; set; }
    internal ItemModel(string text,string id)
    {
        Textvalue = text;
        ID = id;
    }
}

Child Form Containing GridView

namespace SampleApp.Model{
public partial class SeperateWindow : Form
{
    List<ItemModel> _modelList = new List<ItemModel>();
    internal SeperateWindow(List<ItemModel> modelList)
    {
        _modelList = modelList;
        InitializeComponent();
    }

    public void PopulateGrid()
    {
        dataGridView1.DataSource = _modelList;
    }
}

My issue is since everything is in the same project, and model class and child form are in the same Folder too, then also why am i getting Empty Rows? Given that it is working fine if i make them public.

Upvotes: 0

Views: 137

Answers (1)

kennyzx
kennyzx

Reputation: 12993

From MSDN

The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation.

Also please refer to this question, in which the difference between public and internal keywords in databinding has been discussed.

Upvotes: 1

Related Questions