Hi all!
I have a program that runs as a large form (Form1) with smaller forms that open inside of it (PeopleBox). It's for friends/contacts - each person gets their own row in the database (PeopleDB). At runtime I'd like it to open a PeopleBox for each person already existing inside the DB.
I've managed to get it to open a PeopleBox for each row in the DB, but each box is showing the information for the first row only (rather than cycling through the rows). I'm sure I need a foreach statement, but I'm unsure how to phrase it. Any help would be greatly appreciated!
Code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace MaryAnne
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// DB connection
string fileName = "PeopleDB.sdf";
string connectionString = string.Format("DataSource=\"{0}\";", fileName);
// SQL Command
string sql = "select * from PeopleTable";
SqlCeConnection cn = null;
try
{
cn = new SqlCeConnection(connectionString);
SqlCeCommand cmd = new SqlCeCommand(sql, cn);
// Checking to make sure no concurrent connections exist
if (cn.State == ConnectionState.Open)
cn.Close();
// Opening the connection
cn.Open();
SqlCeDataReader scdr = cmd.ExecuteReader();
while (scdr.Read())
{
// Opening a PeopleBox for each row in the DB
PeopleBox childForm = new PeopleBox();
childForm.MdiParent = this;
childForm.Show();
}
scdr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (cn != null)
cn.Close();
}
}
}
}
The relevant bit of code is:
while (scdr.Read())
{
// Opening a PeopleBox for each row in the DB
PeopleBox childForm = new PeopleBox();
childForm.MdiParent = this;
childForm.Show();
}
I know that the while statement is where I'm going wrong. I'm just not having any luck with foreach statements - everything I've tried has thrown up a series of errors.
Thanks for reading!
-MaryAnne