Search code examples
c#data-access-layer

Using Typed DataSets through a Business Logic Layer, access the fields returned


I'm new to 3 tier architecture, I've setup a Data Access Layer using Adapters and I've setup Business Logic to access the Adapters, I can Add, Update, and retrieve data without and issue from code-behind.

Now I'm trying to display a record returned from one of my methods and I can't figure out how to access a rows field value, this seems like it should be straight forward:

    UserManager users = new UserManager();
    var x = users.GetUserByUserID(1);
    txtFirstName.Value = x.FirstNameColumn (only FirstNameColumn is appearing)

But I can't access the FirstName's field value. The GetUserByUserID is returning one record. I know I'm missing something really simple, any help will be much appreciated.


Solution

  • Even though the method is returning only one row, it's still likely to be a row set, so you need to identify the row you want to access (or iterate through the set). Something like:

    txtFirstName.Value = x[0].FirstName
    

    I believe x.FirstNameColumn will give you a reference to the column definition, not the field value.

    You should probably also check that it does return at least one row before attempting to access it:

    if (x.Rows.Count > 0) {
        txtFirstName.Value = x[0].FirstName
    }
    

    This is from memory, so the syntax may be slightly off. Sorry!

    Iterating looks something like this:

    foreach (DataRow row in x.Rows) {
        txtFirstNames.Value += row.FirstName
    }
    

    Or

    for (int i = 0; i < x.Rows.Count; i++)
    {
        txtFirstNames.Value += x[i].FirstName
    }
    

    Again, best guess, from memory :)