我花了好几个小时为动态创建的列创建模板。 这是代码(它不是来自我的主项目,但我简化了代码来重现我的问题):
首先,我创建了一个包含Column设置的类:
public class ColumnBLO
{
public string foreColor { get; set; }
public string backColor { get; set; }
public string Label { get; set; }
}
然后这是我的主窗口的代码:
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;
}
}
}
执行此代码时,不会显示格式,因为我单击标题列(对列进行排序),或者我自己调用Sort方法。
我尝试了很多东西,比如DGV上的Refresh(),Invalidate()和InvalidateColumns(),但没有任何工作......
如果有人可以帮助我; - )
答案 0 :(得分:1)
将foreach
循环替换为以下内容......
...
//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);
}
...
如果您使用DefaultCellStyle
代替CellStyle
,则默认情况下,您的模板会呈现单元格...像Captain Obvious一样)))