vedran

vedran

  • NA
  • 16
  • 0

Using classes to sanitaze code

May 13 2010 6:59 AM
Hello,

I was thinking to post this in WPF forum, but to the best of my knowledge this is pure c# issue.

I have application (WPF) that display values in listbox. I am using SQLite. On the form I have simple buttons named: ADD, EDIT and DELETE. So, just a simple ordinary page.

Every buttons carries a connection code:
 SQLiteConnection conn = new SQLiteConnection(@"data source=...\Debug\bazaa.s3db");
conn.Open();

SQLiteCommand cmd = new SQLiteCommand(" Select * from korisnici", conn);

DataSet1 dt = new DataSet1();

SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);

DataTable tbl = new DataTable();
da.Fill(tbl);

// fill the listview with values
listView1.DataContext = tbl;
conn.Close();


You can imagine how ugly does it luck having code repetition, so I thought to use classes.

I tried making a static class with a method that contains the above mentioned code. Problem is tbl value. I cant return a tbl. I tried converting it to string and returning it. That works, but string shows nothing.

After thinking i come to an idea to have to classes. First class will be called from main code and will  contain this:

 public  class konekcija
{
ListView zomg = new ListView(); // this list view will be copied onto another class

public void konektujme()
{



SQLiteConnection conn = new SQLiteConnection(@"data source=...\Debug\bazaa.s3db");
conn.Open();

SQLiteCommand cmd = new SQLiteCommand(" Select * from korisnici", conn);

DataSet1 dt = new DataSet1();

SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);

DataTable tbl = new DataTable();
da.Fill(tbl);
//listView1.DataContext = tbl;

zomg.DataContext = tbl;
elementi.transfer.DataContext = zomg.DataContext;
conn.Close();

}


Also i thought to create additional static class, in which I will have only this:
static public class elementi 
{

static public ListView transfer = new ListView();

}

And in main code do this:
  konekcija jao = new konekcija();
jao.konektujme();
listView1.DataContext = elementi.transfer;


Please help me with this. I might be close to solution or totally in wrong direction, I really do not know.
Can you please provide me with your solution, or point me to errors in my solution.

Much appreciated.

Answers (2)