how to establish a connection after validating all the fields in a form can any one please help me with code

SqlConnection myConnection = new SqlConnection(<connection string>);

<connection string> in the basic form looks like this:

"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"

You can see other formats at ConnectionStrings.Com.

SqlConnection myConnection = new SqlConnection(<connection string>);

<connection string> in the basic form looks like this:

"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"

You can see other formats at ConnectionStrings.Com.

Thank you for giving reply me sir, In my form there are 4 text boxes and one button. In the button i have established a connection after that i validated the text boxes.But first i want to validate all the text boxes after that only it has to establish a connection how it is possible can u help me sir with code

at first create a referance to a SqlConnection and after you validate create the actuall connection...
put it into an If statment

Let me get this straight. In the button's click code, you have it create a connection to the database, then validate the text boxes? If that's the case, swap your validation & connection code and you're done. If that's not the case, then what do you mean?

Post some of your code and tell us where you're having trouble with it.

//Here I'm explaining for two text boxes and two buttons save and cancel....
//when save is pressed the connection to database is established and the values in
//the two text box is stored table......
//just follow the instructions....it will help



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace sample
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        //Here I like to use a region to warp the SQL Connection.
        #region SQLConnection
        //Here I declare a couple of items i'm gona use and asign the database name.
        public SqlConnection mySqlConnection;
        public String currentDatabase = "database";
        public SqlCommand mySqlCommand;
        public SqlDataReader mySqlDataReader;

        //This is how i'm gona be closing my connection.
        private void closeConn()
        {
            if (mySqlConnection != null)
            {
                if (mySqlConnection.State == ConnectionState.Open)
                {
                    mySqlConnection.Close();
                }
                mySqlConnection.Dispose();
            }
        }

        //Here is where I create my connection.
        private SqlConnection createConn(string database)
        {
            // Here you define your server. Values can not be NULL.        //Database Server Name.
            string myDSN = "SQLEXPRESS01";

            //Local Server Name.
            string myLSN = "your pc name";

            //Define the type of security, 'TRUE' or 'FALSE'.
            string mySecType = "TRUE";

            //Here you have your connection string you can edit it here.
            string mySqlConnectionString = ("server=" + myLSN + "\\" + myDSN + ";database=" + database + ";Integrated Security=" + mySecType);

            //If you wish to use SQL security, well just make your own connection string...
            // I make sure I have declare what mySqlConnection stand for.
            if (mySqlConnection == null) { mySqlConnection = new SqlConnection(); };

            // Since i will be reusing the connection I will try this it the connection dose not exist.
            if (mySqlConnection.ConnectionString == string.Empty || mySqlConnection.ConnectionString == null)
            {
                // I use a try catch stament cuz I use 2 set of arguments to connect to the database
                try
                {
                    //First I try with a pool of 5-40 and a connection time out of 4 seconds. then I open the connection.
                    mySqlConnection.ConnectionString = "Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
                catch (Exception)
                {
                    //If it did not work i try not using the pool and I give it a 45 seconds timeout.
                    if (mySqlConnection.State != ConnectionState.Closed)
                    {
                        mySqlConnection.Close();
                    }
                    mySqlConnection.ConnectionString = "Pooling=false;Connect Timeout=45;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
                return mySqlConnection;
            }
            //Here if the connection exsist and is open i try this.
            if (mySqlConnection.State != ConnectionState.Open)
            {
                try
                {
                    mySqlConnection.ConnectionString = "Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
                catch (Exception)
                {
                    if (mySqlConnection.State != ConnectionState.Closed)
                    {
                        mySqlConnection.Close();
                    }
                    mySqlConnection.ConnectionString = "Pooling=false;Connect Timeout=45;" + mySqlConnectionString + ";";
                    mySqlConnection.Open();
                }
            }
            return mySqlConnection;
        }
        #endregion
        // And there you go you can now connect to the SQL Server



        private void Savebutton_Click(object sender, EventArgs e)
        {


            if (txtbox1.Text.Length != 0 && txtbox2.Text.Length != 0)
            {
                // So all we done erlier is used here In the event we create the connection.
                createConn("vince");
                //We create the command to read the database then we will INSERT or UPDATE.
                mySqlCommand = mySqlConnection.CreateCommand();
                //Here in the command text you put your sql select statment
                mySqlCommand.CommandText = "SELECT txtbox1 = @username FROM table WHERE pass = @pass";
                //I like to set the type of data I will be inserting here. Then I set where will the data come from and repeat for each data string.
                mySqlCommand.Parameters.Add("@username", SqlDbType.VarChar);
                mySqlCommand.Parameters["@username"].Value = txtbox1.Text;

                mySqlCommand.Parameters.Add("@pass", SqlDbType.VarChar);
                mySqlCommand.Parameters["@pass"].Value = txtbox2.Text;
                //I execute the reader.
                mySqlDataReader = mySqlCommand.ExecuteReader();
                if (mySqlDataReader.HasRows)
                {
                    MessageBox.Show("UserName and Password already exist!! Try a new ID");
                }

                // If the database dose not have row i will insert the data otherwise I
                // will just close the connection so I make sure i dont override any thing.
                else
                {
                    mySqlDataReader.Close();
                    //If you had to do an UPDATE here insted of an INSERT statment you would use a UPDATE statement.
                    mySqlCommand.CommandText = "INSERT INTO table(username,pass) VALUES (@username, @pass)";
                    mySqlCommand.ExecuteNonQuery();
                    MessageBox.Show("Successfully Created Login ID");
                }
                //Here you close the Reader and then dispose of the command.
                mySqlDataReader.Close();
                mySqlCommand.Dispose();
                //Normaly i would close the connection here but since i will be makeing
                //a SELECT right away to save the connection i will not close it just yet.
                //You acualy want to close the connection after every group of transaction
                //(don't waite for the user to do something to close the connection,
                //cuz if he just deside to close the browser the connection will stay open. for a long time...)
                //with the database, you don't want to leave it open othewise end users
                //will be put on holt untill the connection expires.
                //closeConn();

                //Now that the data was saved in the database we will do a select
                //from the database and set the text value of the label1 to texBox2.
                // Here we Create the connection to the Table.
                createConn("database");
                mySqlCommand = mySqlConnection.CreateCommand();
                mySqlCommand.CommandText = "SELECT * FROM user_login WHERE username = @username";

                mySqlCommand.Parameters.Add("@username", SqlDbType.VarChar);
                mySqlCommand.Parameters["@username"].Value = txtbox1.Text;

                mySqlDataReader = mySqlCommand.ExecuteReader();
                //Here we use a "while" to set the value to the label
              //   while (mySqlDataReader.Read())
              //  {
                //    label1.Text = Convert.ToString(mySqlDataReader["txtbox2"]);
               // }
                //Here you close the Reader and then dispose of the command adn the connection cuz we are done.
                mySqlDataReader.Close();
                mySqlCommand.Dispose();
                closeConn();
            }
            else
            {
                MessageBox.Show("UserName and Password Cannot be left blank");
            }



        }

        private void Cancelbutton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

       
    }
}



//Just hope this will help you
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.