Search code examples
c#windows-ce

What is the best way to loop through data C#


I want to loop through some data on a device application. For example:

Select name, surname, mail_ad, phone_nr from cust_details

On the form I want to display row by row with next and previous button. For example:

Name: Werner

Surename: VDH

Mail: [email protected]

Phone number: 0716848805

[Previous] [Next]

I've been having a lot of trouble with this. I have used List before but it doesnt work like i want it to work. Can someone please help me here.

How i've been using List:

public List<String> InfoList = new List<String>();
int i = 1;

conn.Open();
string query;
query = "Select name, surname, mail_ad, phone_nr from cust_details";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
   this.InfoList.Add(dr["name"].ToString());
   this.InfoList.Add(dr["surname"].ToString());
   this.InfoList.Add(dr["mail_ad"].ToString());
   this.InfoList.Add(dr["phone_nr "].ToString());
}
dr.Close();
conn.Close();

and then in Next and previous buttons:

if (i + 1 < this.InfoList.Count)
   label1.Text = this.InfoList[++i];
if (i + 1 < this.InfoList.Count)
   label2.Text = this.InfoList[++i];
if (i + 1 < this.InfoList.Count)
   label3.Text = this.InfoList[++i];
if (i + 1 < this.InfoList.Count)
    label4.Text = this.InfoList[++i];


if (i - 1 < this.InfoList.Count)
   label1.Text = this.InfoList[--i];
if (i - 1 < this.InfoList.Count)
   label2.Text = this.InfoList[--i];
if (i - 1 < this.InfoList.Count)
   label3.Text = this.InfoList[--i];
if (i - 1 < this.InfoList.Count)
   label4.Text = this.InfoList[--i];

I'm using labels to display the data in. Problems I have: Sometimes the order of the labels will get mixed up when I hit next. or 1 label will not have any info in it. when I hit previous and there is no more detail left I get exceptions.


Solution

  • I don't know if this is what your looking for, but simply create a class and then use a List<YourClass>. Define it by using List<YourClass> myList = new List<YourClass>();

    To add values to the List you have to create an object of YourClass and define the values there:

    YourClass myClassObject = new YourClass();
    
    myClassObject.name = dr[i].toString(); //This is the database reader 
    

    Class YourClass contains the following properties:

    string name, 
    string surname, 
    string mail_address, 
    string phone_nr.
    

    Properties are written like this and behave like global variables:

    internal string mystring {get; set;}
    

    Then you can loop through this list and use the variables with:

    name_Lbl.Text = this.myList.name[i]; //This is an example.
    

    Then use the OnPress-Event of the buttons to increment or decrement i.

    Edit: Name your classes properly ;)

    Edit 2: For more info about properties CLICK ME