Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8697981
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T01:38:35+00:00 2026-06-13T01:38:35+00:00

I want to create a winform that connect to a database to do things.

  • 0

I want to create a winform that connect to a database to do things. It’s going to have to connect when it opens and then based on what the user clicks, makes queries. I’m not 100% sure what the best course is to open the connection when it loads and make that connection able to be accessed from all the different classes. I have made a test run to get the connection working that opens the DB connection when the user click the button then makes it’s query but I’d like to move the opening of the DB connection to the InitializeComponent() part and then from the components just call to the connection already made.

I have set this up so that it’s run on a case by case but is there a better way to do this? I’m I doing it that only way you can/should?

Here is the test

Form1.Designer.cs

namespace end_of_day
{
    using System.Data.SqlClient;
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;


        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(78, 411);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(147, 64);
            this.button1.TabIndex = 0;
            this.button1.Text = "Test";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 13);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(199, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "ERROR: didn\'t connect to the database.";
            // 
            // button4
            // 
            this.button4.Location = new System.Drawing.Point(78, 201);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(147, 64);
            this.button4.TabIndex = 4;
            this.button4.Text = "Print Out of Stock";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.Click += new System.EventHandler(this.button4_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(306, 523);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "End of day";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button4;
        // NOTE I NEED TO BE ABLE TO CHANGE THE LABEL FROM OTHER CLASSES FIX THIS SOMEHOW
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Net.Mail;

namespace end_of_day
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection myConnection = queries.create_concection();
            try
            {
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("SELECT TOP 100000 ItemName,Price,In_Stock,Vendor_Part_Num FROM Inventory",
                                                         myConnection);
                myReader = myCommand.ExecuteReader();

                String mess = "";
                int i = 0;
                while (myReader.Read())
                {
                    if (i < 10)
                    {

                        mess += myReader["ItemName"].ToString();
                        mess += myReader["Price"].ToString();
                        mess += "\r\n";
                    }
                    i++;
                }
            }
            catch (Exception er)
            {

                DialogResult dlgRes = MessageBox.Show(er.ToString(), "Error",  MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); 

            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            SqlConnection myConnection = queries.create_concection();

            DialogResult dlgRes = MessageBox.Show("Exculde Videos?",
                 "Options",
                MessageBoxButtons.YesNoCancel,
                 MessageBoxIcon.Question);

            String SQL_op = "";
            if (dlgRes == DialogResult.Yes)
            {
                SQL_op = "AND NOT Dept_ID = 'video'";
            }


            try
            {

                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("SELECT TOP 100000 ItemName,Price,In_Stock,Vendor_Part_Num FROM Inventory WHERE In_Stock<1 AND NOT Dept_ID = '006' "+ SQL_op+" ORDER BY Dept_ID",
                                                         myConnection);
                myReader = myCommand.ExecuteReader();

                String mess = "";
                int i = 0;
                while (myReader.Read())
                {
                    if (i < 10)
                    {

                        mess += myReader["ItemName"].ToString();
                        mess += myReader["Price"].ToString();
                        mess += "\r\n";
                    }
                    i++;
                }


                dlgRes = MessageBox.Show("Had " + i + "items including: \r\n" + mess,
                 "Confirm Document Close",
                MessageBoxButtons.YesNoCancel,
                 MessageBoxIcon.Question);

            }
            catch (Exception er)
            {

                dlgRes = MessageBox.Show(er.ToString(), "Error", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);


            }
        }
    }
}

queries.cs

using System;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Web;


namespace end_of_day
{
    public class queries
    {
        public static SqlConnection create_concection()
        {
            Boolean hasConection =true;
            SqlConnection myConnection = new SqlConnection(
                "Data Source=localhost\\SQLEXPRESS;" +
                "Trusted_Connection=true;" +

                "Initial Catalog=TESTDB; " +
                "connection timeout=30"
            );
            try
            {
                myConnection.Open();
            }

                catch (Exception er)
                {
                    hasConection = false;
                    DialogResult dlgRes = MessageBox.Show(er.ToString(), "Error", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                }


            if (hasConection) {
                // THIS SHOULD CHANGE THE LABEL OF THE MAIN FORM
                //Form1 form = new Form1();
                //form.MyMessage = "made it"; 
            }
            return myConnection;
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T01:38:36+00:00Added an answer on June 13, 2026 at 1:38 am

    It’s going to have to connect when it opens and then based on what the
    user clicks, makes queries.
    …
    I have set this up so that it’s run on a case by case but is there a
    better way to do this?

    There is absolutely a better way. Do not open a connection when the form loads, and leave it open.

    A rule of thumb you should always follow is to open a connection only when you require it, and close it as soon as you are done using it. This means in practice you don’t open it until you need to run a query, as close to the actual query execution as possible, and then you close the connection as soon as the query completes.

    I’m not 100% sure what the best course is to open the connection when
    it loads and make that connection able to be accessed from all the
    different classes

    What you are asking about, is how to design your application, and a common answer you will get is to use an n-tier design. You should read up on multitier architectures.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to create a WinForm application that must draw data coming from a
I want create wordpress website into which I want create user management... That means
I want to create a background worker for a WinForm that triggers code whenever
I want create MenuStrip dynamic (in winform C#.Net 4.0) From Database (SQL Server) and
I have a WinForm that I create that shows a prompt with a button.
I'm using a winForm. I have 2 custom controls that I want to add
I want to create a winform component that contains a collection of other elements,
how to create a watermark text box in winForm i want to use in
i want create a custom json data from the mssql 2008 results so that
We have a winform app that has been in development for some time. It

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.