Is there a better way to connect my DB to my Form?











up vote
0
down vote

favorite












I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.



We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.
My Database name is GameStoreLibrary.



using System.Data;
using System.Data.SqlServerCe;

public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(@"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");

private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}

catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}

private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);

try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}

catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}









share|improve this question
























  • Learn about MVVM.
    – SLaks
    Nov 20 at 1:46










  • Do you mean WPF or WinForms?
    – SLaks
    Nov 20 at 1:46










  • that aint WPF...
    – JohnB
    Nov 20 at 1:52










  • Yikes I actually mean WinForms i'm sorry
    – user9046433
    Nov 20 at 1:54










  • Don't try to re-use the same connection object throughout the class. Create and dispose a new object for each query, and only share the connection string. This works better because of a feature called connection pooling.
    – Joel Coehoorn
    Nov 20 at 2:37

















up vote
0
down vote

favorite












I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.



We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.
My Database name is GameStoreLibrary.



using System.Data;
using System.Data.SqlServerCe;

public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(@"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");

private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}

catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}

private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);

try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}

catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}









share|improve this question
























  • Learn about MVVM.
    – SLaks
    Nov 20 at 1:46










  • Do you mean WPF or WinForms?
    – SLaks
    Nov 20 at 1:46










  • that aint WPF...
    – JohnB
    Nov 20 at 1:52










  • Yikes I actually mean WinForms i'm sorry
    – user9046433
    Nov 20 at 1:54










  • Don't try to re-use the same connection object throughout the class. Create and dispose a new object for each query, and only share the connection string. This works better because of a feature called connection pooling.
    – Joel Coehoorn
    Nov 20 at 2:37















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.



We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.
My Database name is GameStoreLibrary.



using System.Data;
using System.Data.SqlServerCe;

public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(@"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");

private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}

catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}

private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);

try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}

catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}









share|improve this question















I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.



We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.
My Database name is GameStoreLibrary.



using System.Data;
using System.Data.SqlServerCe;

public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(@"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");

private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}

catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}

private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);

try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}

catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}






c# winforms sql-server-ce






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 16:24









Jimi

6,48431533




6,48431533










asked Nov 20 at 1:45









user9046433

33




33












  • Learn about MVVM.
    – SLaks
    Nov 20 at 1:46










  • Do you mean WPF or WinForms?
    – SLaks
    Nov 20 at 1:46










  • that aint WPF...
    – JohnB
    Nov 20 at 1:52










  • Yikes I actually mean WinForms i'm sorry
    – user9046433
    Nov 20 at 1:54










  • Don't try to re-use the same connection object throughout the class. Create and dispose a new object for each query, and only share the connection string. This works better because of a feature called connection pooling.
    – Joel Coehoorn
    Nov 20 at 2:37




















  • Learn about MVVM.
    – SLaks
    Nov 20 at 1:46










  • Do you mean WPF or WinForms?
    – SLaks
    Nov 20 at 1:46










  • that aint WPF...
    – JohnB
    Nov 20 at 1:52










  • Yikes I actually mean WinForms i'm sorry
    – user9046433
    Nov 20 at 1:54










  • Don't try to re-use the same connection object throughout the class. Create and dispose a new object for each query, and only share the connection string. This works better because of a feature called connection pooling.
    – Joel Coehoorn
    Nov 20 at 2:37


















Learn about MVVM.
– SLaks
Nov 20 at 1:46




Learn about MVVM.
– SLaks
Nov 20 at 1:46












Do you mean WPF or WinForms?
– SLaks
Nov 20 at 1:46




Do you mean WPF or WinForms?
– SLaks
Nov 20 at 1:46












that aint WPF...
– JohnB
Nov 20 at 1:52




that aint WPF...
– JohnB
Nov 20 at 1:52












Yikes I actually mean WinForms i'm sorry
– user9046433
Nov 20 at 1:54




Yikes I actually mean WinForms i'm sorry
– user9046433
Nov 20 at 1:54












Don't try to re-use the same connection object throughout the class. Create and dispose a new object for each query, and only share the connection string. This works better because of a feature called connection pooling.
– Joel Coehoorn
Nov 20 at 2:37






Don't try to re-use the same connection object throughout the class. Create and dispose a new object for each query, and only share the connection string. This works better because of a feature called connection pooling.
– Joel Coehoorn
Nov 20 at 2:37














2 Answers
2






active

oldest

votes

















up vote
0
down vote














Small Tip :




Try to use a DBConnect class instead of typing connection string every single time and closing the connection.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace InventoryManagementSystem
{
class DBConnect : IDisposable
{


private static String connectionString = @"Data Source=(LocalDB)v11.0;AttachDbFilename=D:PrivateInventoryManagementSystemInventoryManagementSystemInventoryDB.mdf;Integrated Security=True";
public SqlConnection con = new SqlConnection(connectionString);

public DBConnect()
{
try
{
con.Open();
Console.WriteLine("Database connected");
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine("Database Connection Failed");
throw new Exception();
}
}

public void Dispose()
{
con.Close();
}
}
}


After you have this in your project you just have to create an object whenever you want to access the database.



public void getData(){

using(DBConnect db = new DBConnect()){
String q = "select * from TestTable";
SqlCommand cmd = new SqlCommand(q,db.con);
SqlDatareader r = cmd.ExcecuteReader();

}
}


This will automatically close the connections too.






share|improve this answer




























    up vote
    0
    down vote













    To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.



    Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:



    System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385084%2fis-there-a-better-way-to-connect-my-db-to-my-form%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote














      Small Tip :




      Try to use a DBConnect class instead of typing connection string every single time and closing the connection.



      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Data.SqlClient;

      namespace InventoryManagementSystem
      {
      class DBConnect : IDisposable
      {


      private static String connectionString = @"Data Source=(LocalDB)v11.0;AttachDbFilename=D:PrivateInventoryManagementSystemInventoryManagementSystemInventoryDB.mdf;Integrated Security=True";
      public SqlConnection con = new SqlConnection(connectionString);

      public DBConnect()
      {
      try
      {
      con.Open();
      Console.WriteLine("Database connected");
      }
      catch (Exception e)
      {
      Console.WriteLine(e.StackTrace);
      Console.WriteLine("Database Connection Failed");
      throw new Exception();
      }
      }

      public void Dispose()
      {
      con.Close();
      }
      }
      }


      After you have this in your project you just have to create an object whenever you want to access the database.



      public void getData(){

      using(DBConnect db = new DBConnect()){
      String q = "select * from TestTable";
      SqlCommand cmd = new SqlCommand(q,db.con);
      SqlDatareader r = cmd.ExcecuteReader();

      }
      }


      This will automatically close the connections too.






      share|improve this answer

























        up vote
        0
        down vote














        Small Tip :




        Try to use a DBConnect class instead of typing connection string every single time and closing the connection.



        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Data.SqlClient;

        namespace InventoryManagementSystem
        {
        class DBConnect : IDisposable
        {


        private static String connectionString = @"Data Source=(LocalDB)v11.0;AttachDbFilename=D:PrivateInventoryManagementSystemInventoryManagementSystemInventoryDB.mdf;Integrated Security=True";
        public SqlConnection con = new SqlConnection(connectionString);

        public DBConnect()
        {
        try
        {
        con.Open();
        Console.WriteLine("Database connected");
        }
        catch (Exception e)
        {
        Console.WriteLine(e.StackTrace);
        Console.WriteLine("Database Connection Failed");
        throw new Exception();
        }
        }

        public void Dispose()
        {
        con.Close();
        }
        }
        }


        After you have this in your project you just have to create an object whenever you want to access the database.



        public void getData(){

        using(DBConnect db = new DBConnect()){
        String q = "select * from TestTable";
        SqlCommand cmd = new SqlCommand(q,db.con);
        SqlDatareader r = cmd.ExcecuteReader();

        }
        }


        This will automatically close the connections too.






        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote










          Small Tip :




          Try to use a DBConnect class instead of typing connection string every single time and closing the connection.



          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          using System.Threading.Tasks;
          using System.Data.SqlClient;

          namespace InventoryManagementSystem
          {
          class DBConnect : IDisposable
          {


          private static String connectionString = @"Data Source=(LocalDB)v11.0;AttachDbFilename=D:PrivateInventoryManagementSystemInventoryManagementSystemInventoryDB.mdf;Integrated Security=True";
          public SqlConnection con = new SqlConnection(connectionString);

          public DBConnect()
          {
          try
          {
          con.Open();
          Console.WriteLine("Database connected");
          }
          catch (Exception e)
          {
          Console.WriteLine(e.StackTrace);
          Console.WriteLine("Database Connection Failed");
          throw new Exception();
          }
          }

          public void Dispose()
          {
          con.Close();
          }
          }
          }


          After you have this in your project you just have to create an object whenever you want to access the database.



          public void getData(){

          using(DBConnect db = new DBConnect()){
          String q = "select * from TestTable";
          SqlCommand cmd = new SqlCommand(q,db.con);
          SqlDatareader r = cmd.ExcecuteReader();

          }
          }


          This will automatically close the connections too.






          share|improve this answer













          Small Tip :




          Try to use a DBConnect class instead of typing connection string every single time and closing the connection.



          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          using System.Threading.Tasks;
          using System.Data.SqlClient;

          namespace InventoryManagementSystem
          {
          class DBConnect : IDisposable
          {


          private static String connectionString = @"Data Source=(LocalDB)v11.0;AttachDbFilename=D:PrivateInventoryManagementSystemInventoryManagementSystemInventoryDB.mdf;Integrated Security=True";
          public SqlConnection con = new SqlConnection(connectionString);

          public DBConnect()
          {
          try
          {
          con.Open();
          Console.WriteLine("Database connected");
          }
          catch (Exception e)
          {
          Console.WriteLine(e.StackTrace);
          Console.WriteLine("Database Connection Failed");
          throw new Exception();
          }
          }

          public void Dispose()
          {
          con.Close();
          }
          }
          }


          After you have this in your project you just have to create an object whenever you want to access the database.



          public void getData(){

          using(DBConnect db = new DBConnect()){
          String q = "select * from TestTable";
          SqlCommand cmd = new SqlCommand(q,db.con);
          SqlDatareader r = cmd.ExcecuteReader();

          }
          }


          This will automatically close the connections too.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 at 4:34









          Gihan Saranga Siriwardhana

          644418




          644418
























              up vote
              0
              down vote













              To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.



              Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:



              System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;






              share|improve this answer



























                up vote
                0
                down vote













                To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.



                Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:



                System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;






                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.



                  Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:



                  System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;






                  share|improve this answer














                  To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.



                  Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:



                  System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 20 at 17:16

























                  answered Nov 20 at 17:11









                  Rob Simmermon

                  11




                  11






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385084%2fis-there-a-better-way-to-connect-my-db-to-my-form%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Costa Masnaga

                      Fotorealismo

                      Sidney Franklin