我的 Delphi 7 表单中有一个 TComboBox,其中包含一些项目。
在 OnChange
事件中,我根据选择的 Item 进行一些处理,但在此处理过程中我可能想要恢复到之前选择的 Item。
以编程方式,我想要类似的东西
ComboBox.ItemIndex := oldItemIndex;
问题是我不知道如何获取oldItemIndex
。
我尝试在 OnCloseUp 事件中定义一个(全局)变量,但 ItemIndex 已经是新选定的 ItemIndex。
我还尝试在 OnEnter
事件上保存 oldItemIndex
。虽然这适用于在控件第一次获得焦点时保存 oldItemIndex
,但如果焦点保留在其中,则它不起作用,因此仅在项目第一次更改时才有效。
在 OnChange 事件处理程序中获取 ComboBox 中最后一个选定项目的最简单方法是什么?
最佳答案
一种方法是这样的:
type
TForm1 = class(TForm)
ComboBox1: TComboBox;
Edit1: TEdit;
procedure ComboBox1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FPriorIndex : integer;
public
end;
implementation
{$R *.dfm}
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
showmessage(ComboBox1.Items[FPriorIndex]);
FPriorIndex := ComboBox1.ItemIndex;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ComboBox1.ItemIndex := 0;
FPriorIndex := ComboBox1.ItemIndex;
end;
如何在 OnChange 事件之外没有变量的情况下执行此操作:
procedure TForm1.ComboBox1Change(Sender: TObject);
const
PRIOR_INDEX : integer = 0;
begin
showmessage(ComboBox1.Items[PRIOR_INDEX]);
PRIOR_INDEX := ComboBox1.ItemIndex;
end;
为此,您需要打开项目选项/编译器并选中“可分配类型常量”
关于delphi - 如何在 OnChange 事件之前获取 ComboBox ItemIndex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43475024/