2012-11-27 4 views
1

옆에있는 텍스트 상자의 목록 상자에서 선택한 항공편에 대한 정보를 표시하려고합니다. 내 문제는 내 curFlight 변수를 제대로 작동시키지 못한다는 것입니다. InvalidCastException이 처리되지 않았기 때문에 오류가 발생했으며 froim으로 숫자를 캐스팅 할 때 값은 무한대보다 작은 숫자 여야합니다.텍스트 상자의 목록 상자에서 선택된 개체에 대한 정보 표시

을 heres 내 양식 코드

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

namespace Reservations 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     Flight curFlight; 

     Flight flight1 = new Flight("Cessna Citation X", "10:00AM", "Denver", 6, 2); 
     Flight flight2 = new Flight("Piper Mirage", "10:00PM", "Kansas City", 3, 2); 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      MakeReservations(); 
      DisplayFlights(); 

     } 

     private void lstFlights_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      curFlight = (Flight)lstFlights.SelectedItem; 
      txtDepart.Text = curFlight.DepartureTime; 
      txtDestination.Text = curFlight.Destination; 
     } 

     private void MakeReservations() 
     { 
      flight1.MakeReservation("Dill", 12); 
      flight1.MakeReservation("Deenda", 3); 
      flight1.MakeReservation("Schmanda", 11); 
      flight2.MakeReservation("Dill", 4); 
      flight2.MakeReservation("Deenda", 2); 
     } 

     private void DisplayFlights() 
     { 
      lstFlights.Items.Clear(); 
      lstFlights.Items.Add(flight1.Plane); 
      lstFlights.Items.Add(flight2.Plane); 
     } 

     private void btnMakeReservation_Click(object sender, EventArgs e) 
     { 
      string name; 
      int seatNum; 

      name = txtCustomerName.Text; 
      seatNum = Convert.ToInt16(txtSeatNum.Text); 

      curFlight.MakeReservation(name, seatNum); 
     } 
    } 
} 

HERES 클래스 코드는 해당 문자열을 캐스팅하려고 다음 목록 상자에 문자열을 할당하고 있기 때문에 당신이 오류가 발생하는 이유는

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Reservations 
{ 
    class Flight 
    { 
     private string mPlane; 
     private string mDepartureTime; 
     private string mDestination; 
     private int mRows; 
     private int mSeats; 
     private string[] mSeatChart; 

     public Flight() 
     { 
     } 

     public Flight(string planeType, string departureTime, string destination, int numRows, int numSeatsPerRow) 
     { 
      this.Plane = planeType; 
      this.DepartureTime = departureTime; 
      this.Destination = destination; 
      this.Rows = numRows; 
      this.Seats = numSeatsPerRow; 

      // create the seat chart array 
      mSeatChart = new string[Rows * Seats]; 

      for (int seat = 0; seat <= mSeatChart.GetUpperBound(0); seat++) 
      { 
       mSeatChart[seat] = "Open"; 
      } 
     } 

     public string Plane 
     { 
      get { return mPlane; } 
      set { mPlane = value; } 
     } 

     public string DepartureTime 
     { 
      get { return mDepartureTime; } 
      set { mDepartureTime = value; } 
     } 

     public string Destination 
     { 
      get { return mDestination; } 
      set { mDestination = value; } 
     } 

     public int Rows 
     { 
      get { return mRows; } 
      set { mRows = value; } 
     } 

     public int Seats 
     { 
      get { return mSeats; } 
      set { mSeats = value; } 
     } 

     public string[] SeatChart 
     { 
      get { return mSeatChart; } 
      set { mSeatChart = value; } 
     } 


     public void MakeReservation(string name, int seat) 
     { 
      if (seat <= (Rows * Seats) && mSeatChart[seat - 1] == "Open") 
      { 
       mSeatChart[seat - 1] = name; 
      } 
      else 
      { 
       //let calling program know it didnt work. 

      } 
     } 

     public bool IsFull() 
     { 
      return false; 
     } 
    } 
} 
+0

디버거에서 코드를 단계별로 살펴보면 어떤 행에서 예외가 발생합니까? –

+0

curFlight = (비행) lstFlights.SelectedItem; – dsquaredtech

답변

1

과 같이해야한다 보다 일반적인 MVCKarl에 의해, 나는 간단한 경우에 맞게 수있는 더 쉬운 방법을 보여줍니다.

당신은 단순히 Flight 클래스 ToString을 무시할 수

:

class Flight 
{ 
    //your code 

    public override string ToString() 
    { 
     //or anything you want to display 
     return this.Plane; 
    }   
} 

가 다음 목록에 항공편을 추가 할 수 DisplayFlights 방법 편집 :이 후

private void DisplayFlights() 
{ 
    lstFlights.Items.Clear(); 
    lstFlights.Items.Add(flight1); 
    lstFlights.Items.Add(flight2); 
} 

당신의 lstFlights_SelectedIndexChanged 예상대로 작업을 시작할 것입니다 :

private void lstFlights_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    curFlight = (Flight)lstFlights.SelectedItem; 
    textBox1.Text = curFlight.DepartureTime; 
    textBox2.Text = curFlight.Destination; 
} 
+0

을 사용하는 방법을 보여 줬습니다. 완벽하게 작동했습니다! 나는 이것이이 간단한 프로그램을위한 최선의 해결책이라고 생각한다. 선생님은 MVCKarl의 예제와 같은 작업을 목록과 함께했지만 선생님은 다음 분기까지 고급 C#에서 필요한 것 이상이라고 말씀하셨습니다. 감사합니다 콘스탄틴과 MVCKarl! – dsquaredtech

2

비행 물체에

lstFlights.Items.Add(flight1.Plane); // Just say it is named "Plane 1" 
lstFlights.Items.Add(flight2.Plane); // Just say it is named "Plane 2" 


curFlight = (Flight)lstFlights.SelectedItem; // Now you are trying to convert "Plane 2" into a flight object which is incorrect 

SetupFlights에게

private void Form1_Load(object sender, EventArgs e) 
{ 
     MakeReservations(); 
     DisplayFlights(); 
     SetupFlights(); // added this line 
} 

private void SetupFlights() 
{ 
     flightList.Add(flight1); 
     flightList.Add(flight2); 
} 

를 추가 할 양식 부하 유형 항공편의

List<Flight> flightList = new List<Flight>(); 

Flight flight1 = new Flight("Cessna Citation X", "10:00AM", "Denver", 6, 2); 
Flight flight2 = new Flight("Piper Mirage", "10:00PM", "Kansas City", 3, 2); 

을 글로벌 목록을 추가하고 변경 선택한 지수는 대답하지만이

private void lstFlights_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     curFlight = flightList.FirstOrDefault(x => x.Plane == lstFlights.SelectedItem.ToString()); // Changed this line 
     txtDepart.Text = curFlight.DepartureTime; 
     txtDestination.Text = curFlight.Destination; 
} 
+0

이 작업을 수행하는 방법을 이해하지 못합니다. 이제까지 수행 한 첫 번째 과제는 객체 지향이며 클래스의 예제 코드를 살펴보면 도움이되지 않습니다. 나는이 유용한 정보를 얻으려면 어떻게 해야할지조차 모른다. 목록 상자에서 어떤 객체가 선택되었는지 간단히 알기 위해 코드를 작성하고 대상 값과 출발 시간 값을 텍스트 상자에 표시하려면 어떻게해야합니까? – dsquaredtech

+0

오, 내가 너의 편집을 못 봤어. 내가 그걸로 장난감을 치고, 내가 어떤 결과를 얻을 수 있는지 알아봐. 감사! – dsquaredtech

+0

모든 개체를 목록에 넣으십시오 (예제에서와 같이). 그러면 LINQ를 사용하여 개체를 찾을 수 있습니다. 천만에요. 그것은 기초를 배우는 것에 관한 것이고 그 다음에 당신은 잘 할 것입니다. – MVCKarl

관련 문제