Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - 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'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't initialize an instance variable (con) with another instance variable (textBox1).

In many cases it doesn't even really make sense to hold a reference to a database connection as an instance variable. Opening connections is cheap due to connection pooling, you can open one whenever you need and close it when you're done, and you'll be golden.

Do something like this when you need to pull data from your database:

void Foo()
{
    using (var conn = new SqlConnection("..."))
    {
        conn.Open();

        // then read about how to use ADO.NET
    }
}

Also, read about the using block and why it's a good idea.

Bonus chatter: injection on connection strings is a thing, be sure to check user input instead of blindingly incorporating it in your connection string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...