0

I am trying to get data as a list from the database but it is not showing any results. I tried to debug but after this line it doesn't let me to step over / F10:

DataSet ds = new DataSet();
da.Fill(ds);

I am trying to do this by following this example on here: link 1 and here link 2 but finding it difficult hence I thought that I should ask here.

Can someone please explain why it is not displaying the results and as such what I may be doing wrong here? how do I work around and achieve it to display the data?

Here's the full controller code for your inspection:

public static List<DBTrack> GetListOfTracks()
{
    if (DBTrackData == null)
    {
       string myConnectionString = "Data Source="; // I have taken off the source
       string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
       SqlDataAdapter da = new SqlDataAdapter();
       DataSet ds = new DataSet();
       da.Fill(ds);

       OleDbConnection myConnection = new OleDbConnection(myConnectionString);
       OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
       myCommand.Connection.Open();
       OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

       List<DBTrack> list = new List<DBTrack>();
       while (myReader.Read())
       {
           DBTrack data = new DBTrack();
           data.TrackID = (Guid)(myReader["TrackID"]);
           data.AddedDate = (DateTime)myReader["AddedDate"];
           data.TrackName = (string)myReader["TrackName"];
           data.ArtistName = (string)myReader["ArtistName"];
           list.Add(data);
       };
    }

   return DBTrackData;
}

EDIT:

SqlConnection mySQLconnection = new SqlConnection(@"Data Source=server-2\SQLExpress;Initial Catalog=End;Integrated Security=False;User ID=test1;Password=**");
SqlCommand mySelectString = new SqlCommand("SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track");

using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();

using (SqlCommand myCommand = new SqlCommand // The best overload method System.Data.SqlClient.SqlCommand.SqlCommand has some invalid arguments
(mySelectString, mySQLconnection))           // Cannot convert from System.Data.SqlClient.SqlCommand to 'string' 
 {
Community
  • 1
  • 1

2 Answers2

2

You should set the DBTrackData to the result of the list:

while (myReader.Read())
{
    ...
}

DBTrackData = list;

You could also directly edit the DBTrackData in your code:

private static List<DBTrack> DBTrackData
public static List<DBTrack> GetListOfTracks()
{
    if (DBTrackData == null)
    {
       ...

       DBTrackData = new List<DBTrack>();
       while (myReader.Read())
       {
           DBTrack data = new DBTrack();

           ...

           DBTrackData.Add(data);
       };
    }

   return DBTrackData;
}

So, in full it should be:

public static List<DBTrack> GetListOfTracks()
{
    try
    {
        if (DBTrackData == null)
        {
            string myConnectionString = "Data Source="; // I have taken off the source
            string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";

            using (OleDbConnection myConnection = new OleDbConnection(myConnectionString))
            {
               myConnection.Open();

               using (OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection))
               {
                   OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                   List<DBTrack> list = new List<DBTrack>();

                   while (myReader.Read())
                   {
                       DBTrack data = new DBTrack();
                       data.TrackID = (Guid)(myReader["TrackID"]);
                       data.AddedDate = (DateTime)myReader["AddedDate"];
                       data.TrackName = (string)myReader["TrackName"];
                       data.ArtistName = (string)myReader["ArtistName"];

                       list.Add(data);
                   }

                   DBTrackData = list;
               }
            }
        }

        return DBTrackData;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    return DBTrackData;
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • thanks Patrick for the detailed help :) I tried your suggestion too and as same as above comment, the debugger won't let me `step over / F10` pass this line `OleDbConnection myConnection = new OleDbConnection(myConnectionString);`, does this mean that I have connection issue in `string myConnectionString` in order to connect to the `DB`? thanks again :) – user3679123 Jun 17 '14 at 13:15
  • I think so. If it shows a exception to you, you have probably some connection issue. – Patrick Hofman Jun 17 '14 at 13:17
  • thanks - I don't get any exceptions or error messages. It just does not go pass from this line `OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);` of code onwards. – user3679123 Jun 17 '14 at 13:22
  • @user3679123: I updated the code. Can you run this and check which line fails? – Patrick Hofman Jun 17 '14 at 13:24
  • thanks for that :) it's ok .. I tried your suggestion and I get the following error `MessageBox does not exist in the current context`. I tried adding `using System.Windows.Forms` and also by removing removing the `MessageBox` still the debugger doesn't give any message and has same issue. Sorry about this. – user3679123 Jun 17 '14 at 13:48
  • Where are you querying from? – Patrick Hofman Jun 17 '14 at 13:54
  • Got it :) it now threw the following exception: `An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.` How can I pass this exception? I am querying from a DB Table :).. thanks again. – user3679123 Jun 17 '14 at 14:10
  • What database platform? – Patrick Hofman Jun 17 '14 at 14:12
  • SQL Sever.. thanks :) I checked I will need to use `System.Data.OleDb.OleDbConnection` and not `string` to connect. Well I am trying and not 100% sure :) – user3679123 Jun 17 '14 at 14:14
  • Use `SqlConnection` and `SqlCommand` instead. Check here for connection string: http://www.connectionstrings.com/sql-server/ – Patrick Hofman Jun 17 '14 at 14:15
  • thanks for that :) I followed your example and almost got it working. I get two errors that I am trying to fix in the updated edited post above, if you could help. thanks again :) – user3679123 Jun 17 '14 at 14:37
  • Your `mySelectString` is already a command. Place the declaration of that in the using. – Patrick Hofman Jun 17 '14 at 14:53
  • Patrick - thanks for that :) I did exactly what you suggested and now the errors have gone. Though, the `Expectation` now throws this message `"The requested operation requires a SqlClr context, which is only available when running in the Sql Server process."` Furthermore, when I change this `"context connection=true"` to `false`, then the `Exception` throws this message `"Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection."` is there anything that could be done? :) sorry about this and thanks again :) – user3679123 Jun 18 '14 at 09:28
  • I think it is better to ask that in a different question. This question is more a c# problem. And there are a lot with more knowledge about SQL Server than me. – Patrick Hofman Jun 18 '14 at 09:31
  • that's great Patrick - i'll do that. You have been an amazing help :) thanks :) – user3679123 Jun 18 '14 at 09:35
2

Your main problem is that you are using two different ways of getting the data, but the first is only partially implemented. You are using a data adapter and a data reader. Your data adapter isn't even being passed a connection or query, so this is why it is not working. So you can just remove that part of the code.

It's also easier to read if you immediately return when DBTrackData is not null rather than have a big if block over the whole code. You will then have something like:

public static List<DBTrack> GetListOfTracks()
{
   if (DBTrackData != null) return DBTrackData;

   string myConnectionString = "Data Source="; // I have taken off the source
   string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";

   OleDbConnection myConnection = new OleDbConnection(myConnectionString);
   OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
   myCommand.Connection.Open();
   OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

   List<DBTrack> list = new List<DBTrack>();
   while (myReader.Read())
   {
       DBTrack data = new DBTrack();
       data.TrackID = (Guid)(myReader["TrackID"]);
       data.AddedDate = (DateTime)myReader["AddedDate"];
       data.TrackName = (string)myReader["TrackName"];
       data.ArtistName = (string)myReader["ArtistName"];
       list.Add(data);
   };

   //Setting DBTrackData means these values will get returned on every call to GetListOfTracks for this instance of the class
   DBTrackData = list;

   return list;
}
Andy Nichols
  • 2,952
  • 2
  • 20
  • 36
  • @PatrickHofman How do you know that is the purpose? It's some sort of caching mechanism but we can't tell from the question whether it is set every time or whether the calling code determines when it is set. It might be populated daily. I've answered the question asked - why the code fails on a certain line. Whether DBTrackData gets set or not is separate to that point. – Andy Nichols Jun 17 '14 at 07:52
  • Fair enough, I'll edit the answer to set this value with a code comment. – Andy Nichols Jun 17 '14 at 07:56
  • thanks for the detailed answer. It made more sense now :) I tried your suggestion and it still won't display the data from the database. Does it mean that my `myConnectionString` is not connecting to the `DB`? Because the debugger won't let me `step over / F10` pass this line `OleDbConnection myConnection = new OleDbConnection(myConnectionString);`. thanks again :) – user3679123 Jun 17 '14 at 13:10
  • In what way won't it let you? It just hangs or you get an exception? – Andy Nichols Jun 17 '14 at 13:17
  • thanks - I don't get any exception or connection issue. It just does not hit any lines of the code pass from this line onwards `OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);`. – user3679123 Jun 17 '14 at 13:20
  • I would temporarily add a line after you create the connection. Try adding myConnection.Open() and see whether that executes OK. If there are issues with that then I suspect your connection string is wrong. – Andy Nichols Jun 17 '14 at 13:25
  • you're right, I've added the `myConnection.Open()` line with the help of Patrick, and it still doesn't give any errors / exceptions. I suspect the `myConnectionString` to be wrong. thanks again :) – user3679123 Jun 17 '14 at 13:50