I'm creating a WinForms application. I put my connection string in App.config file. Then create the connection string variable
string gLwConnStr = ConfigurationManager.ConnectionStrings["LWConnectionString"].ConnectionString;
string sql = "Select * from Users Where LoginName='" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "'";
string tbl = "User";
DataTable dt = new DataTable(tblName);
SqlDataAdapter da = new SqlDataAdapter(sql, gLwConnStr);
da.Fill(dt);
Does this code look correct? I don't call any .open command like other post so I don't know if I have to close and how to close it. Also I only read data, not write data so I don't use context. Other post suggested "using" but how do I use that in this code? I tried put using around the block it returns red line (like bad syntax)
I saw other post using sqlconnection to open connection then close connection but I don't use it here. How to I close it?
I don't understand why other said this post is the duplicate. Please point it out if you think it is duplication and the answer is already provided. Sorry, I am new to C# language, sometime I don't see small differences.
Can you please suggest how should the code be?
When you pass a string in to a DataAdapter
it will close the connection for you after it does the Fill
. If you pass a SqlConnection
to the adapter it leaves it in whatever state it found it in (If closed it opens it, uses it, then closes it. If open it uses it and does not close it).