如何动态设置stringgrid单元格的颜色
1个回答
展开全部
用stringgrid的DrawCell控制背景色
-------------------------
见下面的demo,界面上放button==>用于填充数据(btn1),放stringgrid==>用于显示数据(strngrd1)
--------------------------
procedure TForm1.btn1Click(Sender: TObject);
const
Cn_Row_Cnt = 3;
Cn_Col_Cnt = 3;
var
iRowNo,iColNo:Integer;
i:Integer;
begin
for i := 0 to Grd1.RowCount -1 do
Grd1.Rows[i].Clear;
Grd1.RowCount := Cn_Row_Cnt;
Grd1.ColCount := Cn_Col_Cnt;
Grd1.FixedCols:=0;
Grd1.FixedRows:=0;
for iRowNo := 0 to Cn_Row_Cnt do
for iColNo := 0 to Cn_Col_Cnt do
Grd1.Cells[iColNo,iRowNo] := Format('第%d行第%d列',[iRowNo,iColNo]);
end;
procedure TForm1.Grd1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
iBackColor,iFrontColor:Integer;
begin
//这里根据你的需要得到各种颜色什么的
case (ARow mod 2) of
0:
begin
iBackColor := clYellow; //背景黄色
iFrontColor := clRed; //字体红色
end;
1:
begin
iBackColor := clSkyBlue;//背景天蓝
iFrontColor := clBlack; //字体黑色
end;
end;
with TStringGrid(Sender) do
begin
Canvas.Brush.Color := iBackColor;
Canvas.Font.Color := iFrontColor;
Canvas.FillRect(Rect);
Canvas.TextRect(Rect,Rect.Left+2,Rect.Top+2,Cells[ACol,ARow]);//没这句话,会没有字的
end;
end;
-------------------------
见下面的demo,界面上放button==>用于填充数据(btn1),放stringgrid==>用于显示数据(strngrd1)
--------------------------
procedure TForm1.btn1Click(Sender: TObject);
const
Cn_Row_Cnt = 3;
Cn_Col_Cnt = 3;
var
iRowNo,iColNo:Integer;
i:Integer;
begin
for i := 0 to Grd1.RowCount -1 do
Grd1.Rows[i].Clear;
Grd1.RowCount := Cn_Row_Cnt;
Grd1.ColCount := Cn_Col_Cnt;
Grd1.FixedCols:=0;
Grd1.FixedRows:=0;
for iRowNo := 0 to Cn_Row_Cnt do
for iColNo := 0 to Cn_Col_Cnt do
Grd1.Cells[iColNo,iRowNo] := Format('第%d行第%d列',[iRowNo,iColNo]);
end;
procedure TForm1.Grd1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
iBackColor,iFrontColor:Integer;
begin
//这里根据你的需要得到各种颜色什么的
case (ARow mod 2) of
0:
begin
iBackColor := clYellow; //背景黄色
iFrontColor := clRed; //字体红色
end;
1:
begin
iBackColor := clSkyBlue;//背景天蓝
iFrontColor := clBlack; //字体黑色
end;
end;
with TStringGrid(Sender) do
begin
Canvas.Brush.Color := iBackColor;
Canvas.Font.Color := iFrontColor;
Canvas.FillRect(Rect);
Canvas.TextRect(Rect,Rect.Left+2,Rect.Top+2,Cells[ACol,ARow]);//没这句话,会没有字的
end;
end;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询