问题
I have a TableLayoutPanel currently with multiple rows + columns. It's populated by a for loop that will be different every time it's run dependant on the output of an SQL Query.
void tblTableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == 2 || e.Row == 4)
{
Graphics g = e.Graphics;
Rectangle r = e.CellBounds;
g.FillRectangle(Brushes.Red, r);
}
}
This is the code I've got currently to colour individual rows, but I'd like to be able to colour individual cells depending on 2 variables (J, and K).
TableLayoutPanel.Controls.Add(label, J, K);
Similarly here is a sample of how I've added a label to a cell in the TableLayoutPanel using J and K. Is it possible to overload the CellPaint method to allow J and K to be used in it? or if so how could I go about re-colouring cells during runtime?
I've asked this question previously and got the following solution;
CellPaint is an event and not a method. I suggest you create a method GetColor(int row,int column) that returns a color Brush and then in the CellPaint event call your method with e.Row and e.Column.
I'm not entirely sure how this would work as the variables I am using are in the main program, wouldn't I then need to compare these with the variables in my method? or set them somewhere to be compared and then after that do the event. Could anyone explain this a bit clearer for me? or maybe give me an example? Thanks.
回答1:
Here is an example:
void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
Graphics g = e.Graphics;
Rectangle r = e.CellBounds;
g.FillRectangle(GetBrushFor(e.Row, e.Column), r);
}
private Brush GetBrushFor(int row, int column)
{
if (row == 2 && column == 1)
return Brushes.Red;
// other logic
// ...
// return default Brush
}
Remark - it looks strange that you want to assign color based on just on row and column index, instead of some business logic (i.e. depending on data displayed in cell).
回答2:
One possible solution is to save j and k in Control.Tag, to example as array of objects and during cell paiting get j and k back from the control what is in this cell.
来源:https://stackoverflow.com/questions/14877012/changing-cell-colours-of-a-tablelayoutpanel-by-variables-during-runtime