I'm learning C# on my own (I know C, Pascal, and about 8 proprietary languages) ... I'm stuck with VS2005 Pro (no budget) so I can't upgrade and I can't use Linq. I'm using Access just for simplicity at this point.
What I'm trying to do, is what I've done in other languages ... build a utility class that does DB work for me. e.g. Pass it a listbox, combobox, datagrid, memo, etc and tell it what data to fill it with by passing the sql command with the call.
I'd like some opinions on if I'm headed in the right direction, and if there's code in this first method, that can be moved up in the class (out of the method itself to eliminate repetition in code) but still available to the other methods I'll be adding.
Or do I have redundant code? Or am I making something more difficult than it is?
Be warned, if you start throwing advanced, cryptic, C# shorthand at me ... I'm going to ask you to explain what I can't research and understand on the web. :)
Here's the class so far;
class DBUtilies
{
public string strDBFile; //see the constructor...
public string strConnStr; //see the constructor...
public DBUtilies()
{
strDBFile = @"C:\C#Projects\FE Informant\FEDB.mdb";
strConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + strDBFile;
}
public void FillListBox(ListBox ls, string sqlCommand)
{
int icnt; // tracks the record count returned.
int x; // a loop variable.
//Set up the connection and adapters...
OleDbConnection myConn = new OleDbConnection();
myConn.ConnectionString = strConnStr;
OleDbCommand sqlCmd = new OleDbCommand(sqlCommand);
OleDbDataAdapter dbAdapter = new OleDbDataAdapter();
dbAdapter.SelectCommand = sqlCmd;
DataSet ds = new DataSet();
ds.Clear();
// Open the connection ....
myConn.Open();
sqlCmd.Connection = myConn;
// Get the data and see how many records we got ....
dbAdapter.Fill(ds, "dbrecs");
icnt = ds.Tables[0].Rows.Count;
// Fill the ListBox ...
if (icnt > 0)
{
ls.Items.Clear();
for (x = 0; x < icnt; x++)
{
ls.Items.Add(ds.Tables[0].Rows[x][0].ToString());
}
}
// Close the connection and toss it...
myConn.Close();
myConn.Dispose();
}
}
What the above class allows me to do is just have two lines of code to handle any listbox, combobox, etc. that I need to fill. Example:
DBUtilies dbu = new DBUtilies();
dbu.FillListBox(listBox1,"SELECT sDesc FROM BookClass");
BTW ... before you beat me up about try/catch and error handling, that will all be added later, I'm trying to keep it simple to get my head wrapped around all this stuff. :)
Thanks guys.