Retrieving from a DataRow

Can I retrieve a field from a DataRow wtihout having to cast it to the correct type

I have a class that contains a DataTable member. The default constructor fills it from a table on an SQL server.

Once created, getters return lookup items from the table, based on received criteria.

The getter methods accept a string or set of strings, apply a Select on the member tables, and set a result string from the data table. For example:

public string getLocationData(string SiteID, string Location)
{
string result;

DataRow[] rows = LocationInfo.Select("Practice = '" + SiteID.Trim() + "' And Location = '" + Location.Trim() + "'");
if(rows.Length > 0)
{
DataRow theRow = rows[0];
result = (string) theRow[2];
}
else
result = "";

return result;
}

Why do I have to do the cast Is there a simpler way to return the data I don't want to continually hit the database every time a lookup is requested, and I am aware of when the database gets updated.



Answer this question

Retrieving from a DataRow

  • Sinc

    Tony,
    you need to cast the data because the compiler cannot know that what you are doing is legal. Doesn't matter that the types will be right at run-time, at compile time it is definitely not, as if you were assigning an object into a string. A nice way around this is to use strong-typed datasets... quite worth the time studying.

    As for your second question, it doesn't look like you are really hitting the DB every time. Anyway, if this is all you do with your Dataset you might want to use some ligther structure. For instance a Hashtable might do in your case, using a combination of SiteID and Location as the hash key. Or even a sorted array, or generic list, in which case you would then use BinarySearch (you need to implement your own comparers).

    HTH
    --mc


  • ashleyhubbard

  • joynt

    Thanks to both of you!

    I just learned about hashtables from another post, and I am using them, rather than member datatables.


  • Retrieving from a DataRow