Как исправить System.InvalidCastException: «Указанное приведение неверно.» - PullRequest
1 голос
/ 21 апреля 2019

У меня есть программа системы бронирования, и в одной форме перечисляются уже сделанные заказы в зависимости от выбранной даты. Все сроки бронирования на выбранную дату должны были отображаться в списке. Выбранный элемент в списке затем заполнит текстовые поля ниже всеми данными бронирования.

Однако я получаю эту ошибку:

System.InvalidCastException: 'Указанное приведение недействительно.'

Это бронированиеКласс:

    public DateTime bookingDate
    {
        get
        {
            return myDate;
        }

        set
        {
            myDate = value;
        }
    }

    public string bookingTime
    {
        get
        {
            return myTime;
        }
        set
        {
            myTime = value;
        }
    }


    public int bookingID
    {
        get
        {
            return myID;
        }
        set
        {
            myID = value;
        }
    }


    public int customerID
    {
        get
        {
            return myCust;
        }
        set
        {
            myCust = value;
        }
    }


    public string bookingTicket
    {
        get
        {
            return myTicket;
        }
        set
        {
            myTicket = value;
        }
    }

    public int bookingQuantity
    {
        get
        {
            return myNum;
        }
        set
        {
            myNum = value;
        }
    }

    public decimal bookingTotal
    {
        get
        {
            return myTotal;
        }
        set
        {
            myTotal = value;
        }
    }


    //A SortedList of booking times is returned for a given Date
    public SortedList GetBookingsByDate(DateTime bookingDate)
    {
        newCon = new System.Data.SqlClient.SqlConnection();

        String firstConStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=";
        String pathToDB = "F:\\Level 5\\Object Oriented Programs\\Programs\\assignmentPractice\\assignmentPractice\\assignmentDB.mdf;";
        String lastConStr = "Integrated Security=True;Connect Timeout=30;User Instance=True";

        newCon.ConnectionString = firstConStr + pathToDB + lastConStr;

        newCon.Open();

        SqlCommand cmBookList = new SqlCommand();
        cmBookList.Connection = newCon;
        cmBookList.CommandType = CommandType.Text;
        cmBookList.CommandText = "Select bookingID, bookingTime from Booking where bookingDate = '" + bookingDate.ToLongDateString() + "'";
        SqlDataReader drBookList = cmBookList.ExecuteReader();

        //This is a sorted list of key/value pairs
        SortedList BookList = new SortedList();

        //drBookList[0] is the key (Booking ID) and drBookList[1] is the value (Booking Time)
        while (drBookList.Read())
        {
            BookList.Add(drBookList[0], drBookList[1]);

        }
        drBookList.Close();
        newCon.Close();
        return BookList;
    }


}

Это форма:

    public bookingSearch()
    {
        InitializeComponent();
    }

    private SortedList BookList;
    private bookingClass objBooking;

    private void btnList_Click(object sender, EventArgs e)
    {
        lstBook.Items.Clear();

        bookingClass objBooking = new bookingClass();

        BookList = objBooking.GetBookingsByDate(DateTime.Parse(dtpDate.Text));

        //Populate the ListBox with the Booking times
        if (BookList.Count == 0)
        {
            lstBook.Items.Add("No Records");
            return;
        }
        foreach (DictionaryEntry book in BookList)
        {
            lstBook.Items.Add(book.Value);
        }
        lstBook.SelectedIndex = 0;


    }

    private void lstBook_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (BookList.Count > 0)     //Don't process if 'No Records'
        {
            //Get the Booking details for a particular selected time in the list
            //The SelectedIndex is used to read the Key value from the
            //SortedList which holds the bookingID
            objBooking.GetBookingsByDate((DateTime)BookList.GetKey(lstBook.SelectedIndex));

            txtID.Text = objBooking.bookingID.ToString();
            txtCust.Text = objBooking.customerID.ToString();
            txtTime.Text = objBooking.bookingTime;
            txtTicket.Text = objBooking.bookingTicket;
            txtNum.Text = objBooking.bookingQuantity.ToString();
            txtTotal.Text = objBooking.bookingTotal.ToString();
        }
    }

}

Эта строка подсвечивается, когда я получаю сообщение об ошибке:

objBooking.GetBookingsByDate((DateTime)BookList.GetKey(lstBook.SelectedIndex))

Любая помощь очень ценится.

...