RONI JATA

RONI JATA

  • NA
  • 5
  • 3.8k

How to populate list view with database records on click event button

Dec 29 2010 1:49 PM
Dear people

I'm trying to display a set of database records on my listview, but for some reason I get this error "Object reference not set to an instance of an object".
Basically on my database table I have serveral records and thay are categorised for instance:
My database table is called Food and the attributes of this table are FoodNameFoodType. The records on the FoodType field are categorised such as:
-Starter -  here are 10 records
-Main -      here are 12 records
-Dessert - here are 10 records

Now what I want is that when I click the Starter Button I want to display on my listview the FoodName of 10 records of the FoodType 'Starter'.

So far I have managed to do this under my Starter click event button (see the code below) but  for some reason i get an error.

 private void cmdStarters_Click(object sender, EventArgs e)
{
OleDbConnectionStringBuilder connBuilder = new OleDbConnectionStringBuilder();
connBuilder.DataSource = @"C:\Users\AP_AE\Desktop\DTPOS_APP\DataBase\DtposMenu.accdb";
connBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connBuilder.Add("Jet OLEDB:Engine Type", "5");

string foodTypeSql = @"SELECT FoodName, FoodType FROM Food WHERE FoodType = @foodType";
using (OleDbConnection conn = new OleDbConnection(connBuilder.ConnectionString))
{
try
{
conn.Open();

OleDbCommand foodsCommand = new OleDbCommand(foodTypeSql, conn);
OleDbParameter foodType = foodsCommand.Parameters.Add("@foodType", OleDbType.VarChar, 15);
OleDbDataAdapter foodsDa = new OleDbDataAdapter(foodsCommand);

foodType.Value = "Starter";
foodsDa.Fill(DtposMenuDS, "Starter");

starterTable = DtposMenuDS.Tables["Food"];

ListViewItem foodItem = new ListViewItem(((DataRowView)DtposMenuBS.Current)["FoodName"].ToString());
this.listViewItemsInStock.Items.Add(foodItem);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}


Could some one please help me on this as I'm a biginner new to C#



Answers (4)