Question

I tried to retrieve data from access database. I wrote the function inside of a class and i got this error. So please anyone know an answer for this question please let me know how can i fix it. the below function is wrote in a class and i need to know how to display data to listview control by using this function and how to call it form load event. i tried to fix this lots of time and i still didn't get a solution for this.

public List<String> displayRoom()
{
    List<String> rooms = new List<String>();

    String query = "select * from room";
    cmd = new OleDbCommand(query, connect);
    reader = cmd.ExecuteReader();
    while(reader.Read()){
        rooms.Add(reader["buyer_name"].ToString());
        rooms.Add(reader["room_type"].ToString());
        rooms.Add(reader["date_from"].ToString());
        rooms.Add(reader["date_to"].ToString());
    }
    return rooms;
}
Was it helpful?

Solution

If you can read data properly from database then just in the form load or constructor of the form class write following line:

//here dbClass is an instance of your database class
List<String> rooms = dbClass.displayRoom(); //though `get/load rooms()` would be more appropriate
foreach (string s in rooms)
  {
    ListViewItem lv=new ListViewItem(s);
    listView1.Items.Add(lv); //listView1 is the ListView instance in your form
  }

EDIT

If your Form has name Form, then either in Form1_Load(object sender, EventArgs e) or in public Form1() constructor (after InitializeComponent is called), you can put the above code.

OTHER TIPS

The ExecuteReader requires an open connection:

connect.Open();

Insert just above

reader = cmd.ExecuteReader();

And close the connection when you are done

}
connect.Close();
return rooms;

See MSDN for more info...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top