2015-12-02 3 views
1

Ниже приведен код, который используется для открытия текстового файла и хранения информации в списке. Но я не уверен, как теперь показать конкретный объект в форме и как вернуться назад и вперед между ними, используя следующую и предыдущую кнопку.Отображение определенного элемента из списка

 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); 
     } 

Вот код im, используемый для отображения объекта, однако он отображает только конечный объект в моем списке.

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; 
    } 

} 

}

+0

У вас есть проблемы, отображающие Информационное поле? – Steve

+0

Информационное поле является частью объекта и отображает его. Проблема, с которой я сталкиваюсь, - это взять конкретный объект из списка и отобразить его. Если это имеет смысл. –

+0

Вероятно, вы должны передать методу DisplayCar объект для отображения. Неясно, в каком контексте вы называете этот метод. Не могли бы вы показать соответствующий код? – Steve

ответ

0

Ваш код дисплей Всегда последний автомобиль, потому что вы используете всегда одной и той же переменной с и добавить их repeteadly в список. Но это закончится списком, полным той же переменной, значения которой считаются в последней строке вашего файла. Вы должны создать новый экземпляр автомобиля внутри цикла и добавить этот экземпляр в свой список (это сохранит значения, прочитанные на определенной строке внутри другого экземпляра машины)

Сказано, что вам нужно целое число, которое сохраняет дорожки текущего автомобиль, взятый из списка и отображается (я переименовал свой c переменных более значимого имя)

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

и после загрузки Карлистского установить этот показатель до нуля

.... 
// 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; 
    .... 
} 

для Навигатора части и до k eep просто, вы можете добавить две простые кнопки в свою форму и назовите их cmdUp и cmdDown. Добавьте связанный обработчик события cmdUp_Click и cmdDown_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(); 
} 
+0

Хорошо спасибо за помощь. Попробуйте это. –

+0

Обновить страницу, я сделал некоторые критические исправления ошибок – Steve

+0

Просто сообщив, что код работает отлично, спасибо очень. –

Смежные вопросы