winforms 如何将对象的详细信息显示到TextBox

qncylg1j  于 2023-01-05  发布在  其他
关注(0)|答案(1)|浏览(131)

我正在做一个程序,它将测试一架飞机是否被允许飞行。这是我第一个使用Windows窗体和C#的个人项目。我取得了很大的进步,但是,我有一个巨大的问题,我想有一个功能。我有两个窗体称为MainFlightSetup,第二个窗体使用一个类称为AircraftClass,它包含构造函数,行为,和性质。

    • 问题**

我会尽量让它简单易懂。我在public void addaircraftButton_Click中调用类AircraftClass来创建一个对象并存储所有必要的细节,如aircraftModelairlineName等。然而,我有一个名为aircraftList的列表框,它只显示飞机名称。详细信息取决于用户从名为detailsList的TextBox内的aircraftList中选择的内容(是的,我是这样叫它的,但它是一个文本框)。这是当问题发生时,它没有显示正确的信息,它显示了AircraftClass的属性值

    • 注**

aircraftList & detailsListMain表单里面-我确实知道这里有一些明显的错误,但我还在学习,请对我宽容点:(
Main表单内的变量

int planeCount = 0; int tailNumber = 0; int planeIndex;
        string planeModel = "NONE"; string airline = "NONE";
        double distanceM = 0.0; double fuelG = 0.0; double maxKG = 0.0; double totalKG = 0.0;
        int passengers= 0; int bag1=0; int bag2 = 0;

主代码(仅限addbuttom方法)

public void addaircraftButton_Click(object sender, EventArgs e)
        {

            FlightSetup addAircraft = new FlightSetup(); //CREATES INFO INSIDE DETAILS

            string nl = "\r\n";

            using (addAircraft)
            {
                DialogResult result = addAircraft.ShowDialog();

                planeModel = addAircraft.planeModel_textbox.Text;
                airline = addAircraft.airline_textbox.Text;

                tailNumber = int.Parse(addAircraft.tailno_textbox.Text);
                passengers= int.Parse(addAircraft.passengerTextBox.Text);
                bag1 = int.Parse(addAircraft.carryonTextBox.Text);
                bag2= int.Parse(addAircraft.checkedBagsTextBox.Text);

                distanceM = double.Parse(addAircraft.distance_textbox.Text);
                fuelG = double.Parse(addAircraft.fuel_textbox.Text);
                maxKG = double.Parse(addAircraft.maxweight_textbox.Text);

                AircraftDetails test = new AircraftDetails(planeModel,airline,tailNumber,passengers,bag1,bag2,distanceM,fuelG,maxKG,totalKG);
                test.AircraftModel = addAircraft.planeModel_textbox.Text;
                MessageBox.Show("Flight Setup is COMPLETED! \n\nPerfom Unit Testing For Take-Off Permission", "FLIGHT SAVED!");

                planeCount++;
                noaircraft_label.Text = planeCount.ToString();
                aircraftList.Items.Add(planeModel + " - REGULAR ROLE");
            }

        }

主代码(仅限aircraftList方法)

public void aircraftList_SelectedIndexChanged(object sender, EventArgs e) //PENDING SOLUTION
        {
            AircraftDetails getData = new AircraftDetails();
            StringBuilder insertData = new StringBuilder(String.Empty);
            string nl = "\r\n";

            planeIndex = aircraftList.SelectedIndex;

            if (planeIndex > -1)
            {
                insertData.Append(getData.AircraftModel.ToString());
                insertData.Append(nl);

                detailsList.Text = insertData.ToString();
            }
        }

飞机等级代码

{
    public class AircraftDetails
    {
        string aircraftModel = "UNKNOWN";
        string airlineName = "UNKNOWN";

        int id = 0; //not in use

        int tailNumber = 0;
        int passengerNo = 0;
        int carrybag = 0;
        int checkbag = 0;
        double distance = 0.0;
        double fuel = 0.0;
        double mWeight = 0.0;
        double totalWeight = 0.0;

        int errorCount = 0;
        
        //Constructors
        public AircraftDetails()
        {
            aircraftModel = "UNKNOWN";
            airlineName = "UNKNOWN";
            id = 0;
            tailNumber = 0;
            passengerNo = 0;
            carrybag = 0;
            checkbag = 0;
            distance = 0.0;
            fuel = 0.0;
            mWeight = 0.0;
            totalWeight = 0.0;
        }
        public AircraftDetails(string aircraftModel, string airlineName, int tailNumber, int passengerNo, int carrybag, int checkbag, double distance, double fuel, double mWeight, double totalWeight)
        {
            this.aircraftModel = aircraftModel;
            this.airlineName = airlineName;
            this.tailNumber = tailNumber;
            this.passengerNo = passengerNo;
            this.carrybag = carrybag;
            this.checkbag = checkbag;
            this.distance = distance;
            this.fuel = fuel;
            this.mWeight = mWeight;
            this.totalWeight = totalWeight;
        }

        //BEHAVIOUR
        public override string ToString()
        {
            if (this.passengerNo >= 1)
            return "Aircraft: " + aircraftModel + "\r\n Tail Number:" + tailNumber + "\r\nOperator: " + airlineName + "\r\nAircraft: " + "\r\nFlight Distance: " + distance + "\r\nFuel: " + fuel +
                "\r\nMax Weight Allowed: " + mWeight + "\r\nTotal Weight: " + totalWeight + "\r\nPassengers: "+passengerNo+ "\r\nCarry-On Bags: "+carrybag+ "\r\nChecked Bags: "+checkbag;
            else
            {
                errorCount++;
                return "Passengers were less than 0\r\nIt means error was recorded\r\nError Count: "+errorCount;
            }
        }

        //Properties
        public string AircraftModel
        {
            get { return aircraftModel; }
            set { aircraftModel = value; }
        }
        public string Airline
        {
            get { return airlineName; }
            set { airlineName = value; }
        }
        public int TailNumber
        {
            get { return tailNumber; }
            set { tailNumber = value; }
        }
        public int PassengerNo
        {
            get { return passengerNo; }
            set { passengerNo = value; }
        }
        public int OnBoardBags
        {
            get { return carrybag; }
            set { carrybag = value; }
        }
        public int CheckedBags
        {
            get { return checkbag; }
            set { checkbag = value; }
        }
        public double FlightDistance
        {
            get { return distance; }
            set { distance = value; }
        }
        public double Fuel
        {
            get { return fuel; }
            set { fuel = value; }
        }
        public double MaxWeight
        {
            get { return mWeight; }
            set { mWeight = value; }
        }
    }
}
tzdcorbm

tzdcorbm1#

您的问题是如何将对象的详细信息显示到TextBox
我在你的代码中看到你在重写ToString方法方面做得很好,在某种意义上,你回答了你自己的问题,因为这就是它所需要的!
但是让我们试着把所有的代码都浓缩到一个minimal reproducible example中,这个minimal reproducible example将包含Jimi正确推荐的数据绑定。

// Minimal example of a class
class AircraftDetails : INotifyPropertyChanged
{
    public override string ToString()
    {
        List<string> builder = new List<string>();
        builder.Add($"{Airline} {Flight}");
        builder.Add($"FlightStatus: {FlightStatus}");
        builder.Add($"{OnboardBags} bags onboard");
        builder.Add($"{CheckedBags} bags checked");
        builder.Add($"Total bags: {TotalBags}");
        builder.Add($"Fuel onboard: {Fuel.ToString("F2")}");
        return string.Join(Environment.NewLine, builder);
    }
    .
    .
    .
    public event PropertyChangedEventHandler? PropertyChanged;
}

接下来,编写主窗体代码以显示从对象到TextBox的详细信息。

一个突出的特点是,ToString()只能在object上调用,因为它是virtual

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        buttonShowObjectInTextbox.Click += onButtonShowObjectInTextbox;
    }
    private void onButtonShowObjectInTextbox(object? sender, EventArgs e)
    {
        // For demonstration purposes, make an object.
        // (Make sure parameterless constructor `AircraftDetails(){ }` is present)
        object o = new AircraftDetails
        {
            Flight = "UA2907",
            Airline = Airline.United,
            Fuel = 50000,
            OnboardBags = 237,
            CheckedBags = 500,
        };
        textBoxMultiline.Text = o.ToString();
    }
}

您的问题还指出**我有一个名为aircraftList...**的列表框。

当列表框绑定到BindingList<AircraftDetails>时,您可以选择AircraftDetails类的属性显示为DisplayMember属性。向主窗体的Load事件添加代码以设置数据源和ListBox

public partial class MainForm : Form
{
    .
    .
    .

    BindingList<AircraftDetails> Details = new BindingList<AircraftDetails>();
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        aircraftDetails.DataSource = Details;
        aircraftDetails.DisplayMember = nameof(AircraftDetails.Flight);
        aircraftDetails.SelectedIndexChanged += onAircraftDetailsSelection;

        // Add a few flights
        Details.Add(new AircraftDetails
        {
            Flight = "UA6026",
            Airline = Airline.United,
            Fuel = 45250,
            OnboardBags = 155,
            CheckedBags = 97,
        });
        Details.Add(new AircraftDetails
        {
            Flight = "UA8888",
            Airline = Airline.United,
            Fuel = 27620,
            OnboardBags = 301,
            CheckedBags = 134,
        });
        Details.Add(new AircraftDetails
        {
            Flight = "WN8610",
            Airline = Airline.Southwest,
            Fuel = 200,
            OnboardBags = 5,
            CheckedBags = 614,
        });
        aircraftDetails.SelectedIndex = -1;
    }

为响应选择更改,调用此方法在文本框中显示对象:

private void onAircraftDetailsSelection(object? sender, EventArgs e)
    {
        if(aircraftDetails.SelectedItem != null)
        {
            textBoxMultiline.Text = aircraftDetails.SelectedItem.ToString();
        }
    }
}

相关问题