user6894907 user6894907 - 2 months ago 10
C# Question

Why is the SqlConnection with Textbox not working?

I'm using this code for connection string:

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

SqlConnection con = new SqlConnection(@"Data Source=" + textBox1.Text + ";Initial Catalog=database;user ID=sa;Password=xxxx");

private void TextBox1.Text_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}


I place it under IntializeCompoment and I get error:


A field initializer cannot reference the non-static field, method, or property 'TransInsert.Form1.textBox1'

Answer

you cannot set connection string using text box outside the event.you can use connection string in form_load event or button_click event like below

using System.Data.SqlClient;
    private void Form1_Load(object sender, EventArgs e)
    {

        SqlConnection con;
        con = new SqlConnection(@"Data Source=" + textBox1.Text + ";Initial Catalog=DBName;user ID=sa;Password=yourpassword");
        con.Open();
    }