显示列表中的特定项目

时间:2015-12-02 17:09:07

标签: c#

以下是用于打开文本文件并将信息存储到列表中的代码。但我不确定如何在表单上显示特定对象以及如何使用下一个和上一个按钮在它们之间前后移动。

        openFileDialog1.ShowDialog();

        currentfile = openFileDialog1.FileName;
        saveToolStripMenuItem.Enabled = true;
        Stream s1 = openFileDialog1.OpenFile();
        StreamReader reader = new StreamReader(s1);
        while (reader.Peek() != -1)
        {
            string str = reader.ReadLine()
            c.ReadString(str);
            cars.Add(c);
        }

以下是用于显示对象的代码,但它只显示列表中的最终对象。

    private void DisplayCar()
    {
        txtBrand.Text = c.Brand;
        txtModel.Text = c.Model;
        txtYear.Text = c.Year;
        txtPrice.Text = c.Price;
        txtNumMiles.Text = c.NumMiles;
        DisplayBody();
        DisplayGear();
        string str = "";
        for (int i = 0; i < c.Information.Count(); i++)
            str += c.Information[i] + "\r\n";
        txtInformation.Text = str;

    }

完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Car_Manager
{
    public partial class Form1 : Form
{
    string currentfile;
    Car c;
    List<Car> cars = new List<Car>();
    public Form1()
    {
        InitializeComponent();
        c = new Car();

        saveFileDialog1.CreatePrompt = true;
        saveFileDialog1.OverwritePrompt = true;
        saveFileDialog1.FileName = "myText";
        saveFileDialog1.DefaultExt = "txt";
        saveFileDialog1.Filter =
            "Text files (*.txt)|*.txt|All files (*.*)|*.*";
    }

    public void clearForm()
    {
        txtBrand.Text = "";
        txtModel.Text = "";
        txtYear.Text = "";
        txtPrice.Text = "";
        txtNumMiles.Text = "";
        txtInformation.Text = "";
        radAutomatic.Checked = false;
        radManual.Checked = false;
        radConvertible.Checked = false;
        radCoupe.Checked = false;
        radEstate.Checked = false;
        radHatchback.Checked = false;
        radHPV.Checked = false;
        radSaloon.Checked = false;
        radSUV.Checked = false;


    }

    private void DisplayCar()
    {
        txtBrand.Text = c.Brand;
        txtModel.Text = c.Model;
        txtYear.Text = c.Year;
        txtPrice.Text = c.Price;
        txtNumMiles.Text = c.NumMiles;
        DisplayBody();
        DisplayGear();
        string str = "";
        for (int i = 0; i < c.Information.Count(); i++)
            str += c.Information[i] + "\r\n";
        txtInformation.Text = str;

    }

    private void FormToObject()
    {
        c.Brand = txtBrand.Text;
        c.Model = txtModel.Text;
        c.Year = txtYear.Text;
        c.Price = txtPrice.Text;
        c.NumMiles = txtNumMiles.Text;
        BodyCheck();
        GearCheck();
    }

    private void BodyCheck()
    {
        if (radHatchback.Checked == true)
        { c.Body = radHatchback.Text;}

        else if (radHPV.Checked == true)
        { c.Body = radHPV.Text;}

        else if (radSUV.Checked == true)
        { c.Body = radSUV.Text;}

        else if (radSaloon.Checked == true)
        { c.Body = radSaloon.Text;}

        else if(radConvertible.Checked == true)
        { c.Body = radConvertible.Text;}

        else if (radCoupe.Checked == true)
        { c.Body = radCoupe.Text;}

        else if (radEstate.Checked == true)
        { c.Body = radEstate.Text;}

    }

    private void DisplayBody()
    {
        if(c.Body == "Hatchback")
        {radHatchback.PerformClick();}

        else if (c.Body == "HPV")
        { radHPV.PerformClick();}

        else if (c.Body == "SUV")
        { radSUV.PerformClick();}

        else if (c.Body == "Convertible")
        { radConvertible.PerformClick();}

        else if (c.Body == "Saloon")
        { radSaloon.PerformClick();}

        else if (c.Body == "Coupe")
        { radSaloon.PerformClick();}

        else if (c.Body == "Estate")
        { radEstate.PerformClick();}
    }

    private void GearCheck()
    {
        if(radAutomatic.Checked == true)
        { c.GearBox = radAutomatic.Text;}

        else if( radManual.Checked == true)
        { c.GearBox = radManual.Text;}
    }

    private void DisplayGear()
    {
       if (c.GearBox == "Manual")
        { radManual.PerformClick();}

       else if (c.GearBox == "Automatic")
        { radAutomatic.PerformClick(); }
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // Open the dialog box to open a file
        // Open a file an load the information from the file
        openFileDialog1.ShowDialog();
        // Retrieve the file name
        currentfile = openFileDialog1.FileName;
        saveToolStripMenuItem.Enabled = true;
        // Open the file and upload the information
        Stream s1 = openFileDialog1.OpenFile();
        //  Create the steamreader reader object thanks to the stream s1
        StreamReader reader = new StreamReader(s1);

        //  Read the first line of the streamreader object
        while (reader.Peek() != -1)
        {
            string str = reader.ReadLine();


            // transform str to a football player
            c.ReadString(str);
            cars.Add(c);
        }

        DisplayCar();

        // display the football player in the form
        reader.Close();
    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // Save everything in a dialog box
        saveFileDialog1.ShowDialog();
        // Open the file and save the information
        Stream textOut = saveFileDialog1.OpenFile();
        StreamWriter writer = new StreamWriter(textOut);
        foreach (Car car in cars)
        {
            string str = c.GetToString();
            writer.WriteLine(str);
        }
         writer.Close();
    }

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // Save the file with the current file name
        FileStream f1 = new FileStream(currentfile,
                FileMode.Create, FileAccess.Write);
        StreamWriter writer = new StreamWriter(f1);
        // get the object into a string
        FormToObject();
        string str = c.GetToString();
        // write the string into the file
        writer.WriteLine(str);
        writer.Close();
    }

    private void btnAddInfo_Click(object sender, EventArgs e)
    {
        c.Information.Add(txtAddInfo.Text);
        string str = "";
        for (int i = 0; i <c.Information.Count(); i++)
            str += c.Information[i] + "\r\n";
        txtInformation.Text = str;
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        txtInformation.Text = "";
    }

    private void addToolStripMenuItem_Click(object sender, EventArgs e)
    {
        clearForm();
    }

    private void btnPreviousCar_Click(object sender, EventArgs e)
    {

    }

    private void btnNextCar_Click(object sender, EventArgs e)
    {


    }

    private void button1_Click(object sender, EventArgs e)
    {

        int a = cars.Count;
        textBox1.Text = Convert.ToString(cars[2]);
    }
}

class Car
{
    //List of properties
    private string brand;
    private string model;
    private string year;
    private string price;
    private string numMiles;
    private string body;
    private string gearbox;
    private List<string> information;

    //Constructor

    public Car() //Default Constructor
    {
        brand = "Unknown";
        model = "Unknown";
        year = "Unknown";
        price = "Unknown";
        numMiles = "Unknown";
        information = new List<string>();
    }

    public Car(string str)
    {
        information = new List<string>();
        ReadString(str);
    }

    public void ReadString(string str)
    {
        string[] words = str.Split('|');
        int Nwords = words.Count();
        brand = words[0];
        model = words[1];
        year = words[2];
        price = words[3];
        numMiles = words[4];
        body = words[5];
        gearbox = words[6];
        information.Clear();
        for (int i = 7; i < Nwords; i++)
            information.Add(words[i]);
    }

    //Methods
    public string Brand
    {
        get { return brand; }
        set { brand = value; }
    }

    public string Model
    {
        get { return model; }
        set { model = value; }
    }

    public string Year
    {
        get { return year; }
        set { year = value; }
    }

    public string Price
    {
        get { return price; }
        set { price = value; }
    }

    public string NumMiles
    {
        get { return numMiles; }
        set { numMiles = value; }
    }

    public string Body
    {
        get { return body; }
        set { body = value; }
    }

    public string GearBox
    {
        get { return gearbox; }
        set { gearbox = value; }
    }

    public List<string> Information
    {
        get { return information; }
        set { information = value; }
    }

    public string GetToString()
    {
        string str = "";
        str += brand + "|";
        str += model + "|";
        str += year + "|";
        str += price + "|";
        str += numMiles + "|";
        str += body + "|";
        str += gearbox + "|";
        for (int i = 0; i < information.Count(); i++)
            str += information[i] + "|";
        return str;
    }

}

}

1 个答案:

答案 0 :(得分:0)

您的代码显示始终是最后一辆车因为您使用始终相同的变量c并将其重复添加到列表中。但是这将以一个完整相同变量的列表结束,其值是在文件的最后一行读取的值。您应该在循环中创建Car的新实例,并将该实例添加到列表中(这将保留在不同汽车实例内的特定行上读取的值)

说,您需要一个整数来保存从列表中获取的当前汽车的曲目并显示(我已将您的c变量重命名为更有意义的名称)

public partial class Form1 : Form
{
    string currentfile;
    Car currentCar = null;
    int curIndex = -1;
    List<Car> cars = new List<Car>();
    ....

加载carList后,将此索引设置为零

....
//  Read the first line of the streamreader object
while (reader.Peek() != -1)
{
    string str = reader.ReadLine();

    // A new instance of a car at every loop
    Car c = new Car();
    c.ReadString(str);
    cars.Add(currentCar);
}

// Set the current index of the car displayed
curIndex = 0;

// take that element from the list like it was an array
currentCar = cars[curIndex];

// start the Whole process of displaying the currentCar
DisplayCar();
....

private void DisplayCar()
{
    txtBrand.Text = currentCar.Brand;
    ....
}

对于导航器部件并保持简单,您可以在表单中添加两个简单的按钮,并将其命名为cmdUpcmdDown。添加相关的事件处理程序cmdUp_ClickcmdDown_Click

private void cmdUp_Click(object sender, EventArgs e)
{
     // Increment and check if we are out of bounds
     curIndex++;
     if(curIndex >= cars.Count)
         // rollover to the beginning              
         curIndex = 0; 
         // (or just curIndex-- to stop at the end of the list)


     currentCar = carsList[curIndex];
     DisplayCar();
}

private void cmdDown_Click(object sender, EventArgs e)
{
     curIndex--;
     if(curIndex < 0)
         // rollover to the end 
         curIndex = cars.Count - 1;     
         // (or just curIndex = 0 to stop at the begin of the list)

     currentCar = carsList[curIndex];
     DisplayCar();
}