Home > Back-end >  Editing column header title in datagridview using Entity Framework
Editing column header title in datagridview using Entity Framework

Time:01-26

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

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

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

CodePudding user response:

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

CodePudding user response:

You should almost never give up setting DataSource.

As mentioned in the first comment under the answer, if you set enter image description here

  • Related