Storing Individual Values From List Box As Variables

70 views Asked by At

I have a listbox which is currently reading fields from my database. I would like to be able to store each individual values that I am reading in as strings and ints. There will four field types, these are Surname, Forename, EmployeeID, PaymentDate. How do I split and store the selected item of combined fields as separate variables.

 foreach (DataRow dr in dsEmployeePayment.Tables["EmployeePayment"].Rows)  
 {
    lstPaymentID_Edit.Items.Add(
    dr["Surname"].ToString() + ", " 
    + dr["Forename"] + ", " 
    + dr["EmployeeID"].ToString() + ", " 
    + dr["PaymentDate"].ToString());
}
1

There are 1 answers

0
Bas On BEST ANSWER

Consider creating an object for the items you are adding to the ListBox.

public class Employee 
{
    public string Surname { get; set; }
    public string Forename { get; set; }
    public int EmployeeID { get; set; }
    public DateTime PaymentDate { get; set; }

    public override string ToString()
    {
        return string.Join(", ", Surname, Forename, EmployeeID, PaymentDate);
    }
 }

Your class will contain all the fields in the correct types. The ListBox will call ToString on your item, and display it in the same fashion as you do now.

The DataRow processing would happen like this:

foreach (DataRow dr in dsEmployeePayment.Tables["EmployeePayment"].Rows)  
{
   lstPaymentID_Edit.Items.Add(
      new Employee {
         Surname =  (string)dr["Surname"],
         Forename = (string)dr["Forename"],
         EmployeeID = (int)dr["EmployeeID"],
         PaymentDate = (DateTime)dr["PaymentDate"]
      }
   );
}

The real magic happens when you do something with the selected item:

Employee selectedEmployee = lstPaymentID_Edit.SelectedItem as Employee;
DateTime paymentDate = selectedEmployee.PaymentDate;