Reputation: 31
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.
Upvotes: 2
Views: 388
Reputation: 125197
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:
Upvotes: 2
Reputation: 5986
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):
Upvotes: 1