Reputation: 402
I try for hours to create templates for columns created dynamically. Here's the code (It's not from my main project but I simplified the code to reproduce my issue) :
First, I created a class containing the Column setting :
public class ColumnBLO
{
public string foreColor { get; set; }
public string backColor { get; set; }
public string Label { get; set; }
}
Then here's the code for my main window :
private Dictionary<string, DataGridView> dgViews;
private List<ColumnBLO> columns;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tabControl1.TabPages.Clear();
tabControl1.TabPages.Add(new TabPage("laUNe"));
//Simulating Format settings
columns = new List<ColumnBLO>();
columns.Add(new ColumnBLO { backColor = "Black", foreColor = "Black", Label = "one" });
columns.Add(new ColumnBLO { backColor = "Blue", foreColor = "Blue", Label = "two" });
columns.Add(new ColumnBLO { backColor = "Red", foreColor = "Red", Label = "three" });
//Creating datagridviews and populate with data
dgViews = new Dictionary<string, DataGridView>();
DataGridView dgv = new DataGridView();
DataTable dt = new DataTable("laTable");
dt.Columns.Add("one");
dt.Columns.Add("two");
dt.Columns.Add("three");
dt.Rows.Add("un", "deux", "trois");
dt.Rows.Add("un", "dos", "tres");
dt.Rows.Add("uno", "due", "tre");
dgv.DataSource = dt;
dgViews.Add("one", dgv);
tabControl1.TabPages[0].Controls.Add(dgv);
//Formatting
foreach (DataGridViewColumn dgvcol in dgViews["one"].Columns)
{
ColumnBLO colB = columns.Where(x => x.Label == dgvcol.HeaderText).First();
DataGridViewCell dgvc = new DataGridViewTextBoxCell();
dgvc.Style.BackColor = Color.FromName(colB.backColor);
dgvc.Style.ForeColor = Color.FromName(colB.foreColor);
dgvcol.CellTemplate = dgvc;
}
}
}
When I execute this code, the formatting is not displayed, since I click on a header column (to sort the column), or if I invoke myself the Sort method.
I tried a lot of things like Refresh(), Invalidate() and InvalidateColumns() on the DGV but nothing's working...
If someone could help me ;-)
Upvotes: 1
Views: 2587
Reputation: 17176
Replace your foreach
loop with the following...
...
//Formatting
foreach(DataGridViewColumn dgvcol in dgViews["one"].Columns)
{
ColumnBLO colB = columns.First(x => x.Label == dgvcol.HeaderText);
dgvcol.DefaultCellStyle.BackColor = Color.FromName(colB.BackColor);
dgvcol.DefaultCellStyle.ForeColor = Color.FromName(colB.ForeColor);
}
...
If You use DefaultCellStyle
instead of CellStyle
cells would be rendered by your template by default... Soulds like Captain Obvious )))
Upvotes: 1