Search code examples
c#.netoracle-databaseodac

use connection with different forms c#


I have a form say form1 in C# the user has to put database name username password in the textboxes of form1. Once the connection is established form2 will open which will display data with predefined sqls. Also additional forms are needed to use the same connection string.How can i achieve this. I am using ODAC to connect to oracle database.

This is the code

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 Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;


namespace Sparrow1
{
    public partial class connectform : Form
    {
        public connectform()
        {
            InitializeComponent();                       
        }

        private OracleConnection conn = new OracleConnection();

        private void button1_Click(object sender, EventArgs e)
        {               
            conn.ConnectionString = "User Id=" + username.Text +
            ";Password=" + password.Text +
            ";Data Source=" + dataSource.Text + ";";

            try
            {
                conn.Open();
                button1.Enabled = false;
                statuslabel.Text = "Success";
                this.Hide();
                overviewform oviewform = new overviewform();
                oviewform.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                statuslabel.Text = "Failed";
            }
            finally
            {
                conn.Dispose();             
            }
        }
    }
}

Solution

  • create a public static string variable named connectionString in Form1.cs

    public static string connectionString 
    

    get its value from other forms by Form1.connectionString;

    Form1.connectionString;