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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…