Delphi中DbGrid控件可以通过设置PickList 以便在单元格中显示下拉列表,而StringGrid没有相关属性,遇到这样的情况主要涉及到以下几个问题:
1、如何在StringGrid某单元格中显示ComboBox
2、如何将ComboBox中的值传递给该单元格
3、如何控制StringGrid控件的Tab跳转
窗体上添加一个StringGrid控件名称为grdGrade,一个ComboBox控件名称为ComboBox1
主要代码如下:
procedure TForm1.grdGradeDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
ColSet:set of 2..5;//哪些列中的单元格需要绑定下拉列表
begin
if (gdfocused in state) then
begin
if (Acol in ColSet) then
begin
combobox1.SetBounds(rect.Left+grdGrade.Left+1,rect.Top+grdGrade.Top+1,rect.Right-rect.Left+2,rect.Bottom-rect.Top+2);//绑定单元格,本来可以不加2的,总是发现ComboBox的size要比单元格小,所以干脆膨胀好了
ComboBox1.Visible:=true;
ComboBox1.SetFocus;
end;
end;
end;
procedure TForm1.grdGradeSetEditText(Sender: TObject; ACol, ARow: Integer;
const Value: String);
var
ColSet:set of 2..5;
begin
if (Acol in ColSet) then
begin
ComboBox1.Text:=Value;//这主要考虑一个问题,如果某单元格显示了ComboBox,然后我想法设法的选中该单元格本身,然后输入数据。如果不存在此语句,ComboBox中将不会显示输入的数据。
end;
end;
procedure TForm1.ComboBox1Exit(Sender: TObject);
begin
ComboBox1.Visible:=false;
ComboBox1.Text:='';
grdGrade.SetFocus;//此事件主要目的是保证StringGrid中Tab可以正常跳转到下一个单元格
if (grdGrade.Col <> grdGrade.ColCount-1) then
grdGrade.Col:=grdGrade.Col + 1
else if (grdGrade.Col = grdGrade.ColCount - 1) and (grdGrade.Row <> grdGrade.RowCount-1) then
begin
grdGrade.Col:=1;
grdGrade.Row:=grdGrade.Row+1;
end
else
begin
grdGrade.Col:=0;//这如果不这样跳转,将在最后一个单元格出不停的循环显示ComboBox
grdGrade.Row:=0;
end;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
grdGrade.Cells[grdGrade.Col,grdGrade.Row]:=Trim(ComboBox1.Text);//传值给StringGrid
end;
测试环境:Delphi7+Windows XP