Amigo Amigo - 6 days ago 6
C# Question

Sql Data Adapter not fetching data

I have the following code:

string q = "SELECT 1";
using (var sqlCommand = new SqlCommand())
{
sqlCommand.CommandText = q;
sqlCommand.Connection = new SqlConnection(DataAccess.ConnectionString);

DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection(DataAccess.ConnectionString))
{
try
{
connection.Open();
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
{
sqlAdapter.SelectCommand = sqlCommand;
sqlAdapter.Fill(dt);
}
}
catch (Exception ex)
{
dt = null;
}
finally
{
connection.Close();
}
}
}


been altering the code structure and try debug, but still couldn't get the data to be fetched every single time. The
dt
value in the end is always
{}
. The connection string is correct because been tried with the alternate solution with
SqlDataReader ExecuteReader()
, the data is fetched no problem.

Answer

Your code works for me - I get a DataTable with one value 1.

Add string result = dt.Rows[0][0].ToString(); after Fill()

To get the result during debugging, you have to click the magnifier icon after Fill() was called:

enter image description here