-1

Im trying to get my connection string from one form to another but it keeps passing NULL Im new to working with different classes so it could be a verry simple mistake.

Form 1

public partial class Form1 : Form
{
    private string ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Ruben\Documents\dbPlatenCompany.mdf;Integrated Security = True; Connect Timeout = 30";
    public Form1()
    {
        InitializeComponent();
    }

    public string getConnectionString()
    {
        return ConnectionString;
    }

    private void btn_login_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConnectionString);
        SqlDataAdapter sqa = new SqlDataAdapter("Select count(*) From tblLogin where Username ='" + txt_username.Text + "' and Password ='" + txt_password.Text + "'", con);
        DataTable dt = new DataTable();
        sqa.Fill(dt);

        if (dt.Rows[0][0].ToString() == "1") 
        {
            this.Hide();
            Form2 main = new Form2();
            main.Show();
        }

        else
        {
            MessageBox.Show("Username or Password is incorrect");
            txt_username.Clear();
            txt_password.Clear();
        }
    }
}

Form 2

public partial class Form2 : Form
{
    private Form1 form1;
    public Form2()
    {
        InitializeComponent();
    }

    private void btn_search_Click(object sender, EventArgs e)
    {
        if (rb_Artist.Checked == true)
        {
            String ConnectionString = form1.getConnectionString();
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlDataAdapter sqa = new SqlDataAdapter("SELECT * FROM tblArtist where Name like" + txt_search.Text, con);
            DataTable dt = new DataTable();
            sqa.Fill(dt);
            dataGridView1.DataSource = dt;
        }
    }
}
er-sho
  • 9,581
  • 2
  • 13
  • 26
im_ Ruben
  • 87
  • 2
  • 10

2 Answers2

3

It's because you never actually initialize Form1 in your Form2.

Change private Form1 form1; to private Form1 form1 = new Form1();

Niklas7
  • 173
  • 8
  • 2
    Thanks alot I didnt even realise it after trying for over an hour! – im_ Ruben Nov 15 '18 at 12:11
  • No problem also just a tip if you want to use variables like connection strings in several forms or classes configure them in the app.config file. You can access and change them more easy than trying to pass them from form to form. . – Niklas7 Nov 15 '18 at 12:24
-1

public static string ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Ruben\Documents\dbPlatenCompany.mdf;Integrated Security = True; Connect Timeout = 30";

using in Form2 not create form1 object

String ConnectionString = form1.ConnectionString

this variable try to solve this problem