将组合框项目写入文件?

时间:2014-03-28 12:30:53

标签: delphi combobox pascal

我创建了一个TComboBox,其中显示了一个包含约30个项目列表的下拉菜单。
当我从程序列表中选择一个项目时,它不会写入我的文件,但表格的其他TEdit部分是。
如何将组合框中的这些项目分配给字符串以便将它们写入文件? 关于如何编写将执行此操作的过程,我不知道如下所示,

unit AddStudent2;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ExtCtrls, ActnList;

CONST
  Filename = 'c:\COMP4\StudentList.txt';

type
  NewStudent = Record
          Name : string [10];
          Surname : string [10];
          TutorGroup : string [10];
          CareerPreference : string [10];
          ID : Integer;
  end;

StudentList = file of NewStudent;

  { TAddStudent }
  TAddStudent = class(TForm)
    AddStudentButton: TButton;
    CareerList: TComboBox;    //item i need help with//
    Label1: TLabel;
    LabelChecker: TLabel;
    StudentForenameEntry: TEdit;
    StudentTutorGroup: TLabel;
    StudentSurnameEntry: TEdit;
    StudentSurname: TLabel;
    StudentName: TLabel;
    StudentPreferredSubject1: TLabel;
    StudentTutorGroupEntry: TEdit;
    procedure ButtonAddStudentClick(Sender : TObject);
    end;

{StudentForm}
var
  StudentForm: TAddStudent;
  StudentRec : NewStudent;
  StudentFile : StudentList;
  MyList : TStringList;
  i : integer;
  TextDrop : String;

implementation
uses
  StudentAddNotifier, SubjectError;
{$R *.lfm}



Procedure TAddStudent.ButtonAddStudentClick(Sender : TObject);
begin
  AssignFile(StudentFile,'c:\COMP4\v2\rsd\sa\COMP44\StudentList.txt');
  StudentRec.Name:= StudentForenameEntry.Text;
  StudentRec.Surname:= StudentSurnameEntry.Text;
  StudentRec.TutorGroup:= StudentTutorGroupEntry.Text; 
  begin
  begin
   StudentRec.CareerPreference  :=     CareerList.Items[CareerList.ItemIndex] ;
    reset(StudentFile);
  seek(StudentFile,System.FileSize(StudentFile));
  write(StudentFile,StudentRec);
  CloseFile(StudentFile);      
    reset(StudentFile);
    seek(StudentFile,System.FileSize(StudentFile));  
    write(StudentFile,StudentRec);
    CloseFile(StudentFile);  
    StudentForm.Close;
    Form3.show; 
  end;
end;

2 个答案:

答案 0 :(得分:1)

如果TComboBox.Items不等于-1,只需通过TComboBox.ItemIndex访问ItemIndex。 (-1表示未选择任何项目。)

var
  CareerItem: string;
begin
  if Career.ItemIndex <> -1 then
  begin
    CareerItem := CareerList.Items[ComboBox1.ItemIndex];
    // Do whatever with CareerItem
  end;
end;

答案 1 :(得分:0)

使用ItemIndex时,您还可以使用Text属性获取当前所选的项目:StudentRec.CareerPreference := Careerlist.Text; 请注意,如果用户在组合框中键入了您将获得该文本的内容,那么您可能希望通过将组合框设置为只读来禁用它。