2

I want to edit column title in datagridview using Entity Framework. I added column and design name with form design, but when I add datasource in code, the columns with data appear in the left, and the columns I created with form design appear with blank. How can I use column design name to fill data from datasource?

I tried many things like

column[0].headercell.value = "column title"

but I don't want that. I want to use column design name.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    You forgot to set the Columns' `DataPropertyName` (it can be set either in the Designer or at run-time) – Jimi Jan 25 '23 at 06:17

2 Answers2

1

Based on my test, I reproduced your problem. I suggest that you could give up datagridview1.DataSource=context.students.ToList().

If you only need to show the columns that you edited in winform, I recommend that you could use reflection and loop to do it.

Here is a code example you could refer to.

  private void Form1_Load(object sender, EventArgs e)
    {
        Model1 model = new Model1();//DbContext
        foreach (var item in model.Students)
        {
            dataGridView1.Rows.Add();
        }
        var columns = dataGridView1.Columns;
        for (int i = 0; i < dataGridView1.ColumnCount; i++)
        {
            var names = model.Students.ToList().Select(x => x.GetType().GetProperty(columns[i].Name).GetValue(x)).ToList();
            for (int j = 0; j < names.Count(); j++)
            {
                dataGridView1.Rows[j].Cells[dataGridView1.Columns[i].Name].Value = names[j].ToString();

            }
        }
       
    }

Tested result(Only show the Id and Age column): enter image description here

Jack J Jun
  • 5,633
  • 1
  • 9
  • 27
  • 1
    You should almost never give up setting DataSource. As mentioned in the first comment under the answer, if you set `DataPropertyName` for the column, then it will not be added again. Even if you want to only show a few of the columns, just add them, and set `AutogenerateColumns` to false, to prevent adding undesired columns. You can also decorate the property with `[Browsable(false)]` to prevent adding it. – Reza Aghaei Jan 25 '23 at 15:50
1

You should almost never give up setting DataSource.

As mentioned in the first comment under the answer, if you set DataPropertyName for the column, then it will not be added again after setting data source.

Even if you want to only show a few of the columns, just add them to the DataGridView columns collection, and make sure you set AutogenerateColumns to false, to prevent adding undesired columns.

If you do not wan to add the columns manually or set the header texts manually, then you can decorate the property with [Browsable(false)] to prevent showing the column in DataGridView, and useing [DisplayName("The title")] attribute to assign header text.

And finally you may be interested in the following posts:

enter image description here

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398