SausageFingers
SausageFingers

Reputation: 1846

Return a single row from a Strongly Typed Dataset

In my C# ASP.Net project I am using a xsd dataset to link to my database. I want to create a function return a single row from the strongly typed datatable but I'm running into a little difficulty doing this in C#. I have previously done this in VB.Net successfully using the code:

Public Function dr() As DataSet1.UsersRow
    Dim ta As New DataSet1TableAdapters.UsersTableAdapter
    Dim dt As DataSet1.UsersDataTable = ta.GetData
    Return dt.Rows(0)
End Function

My C# version of the code is:

public DataSet1.UsersRow dr()
{
    DataSet1TableAdapters.UsersTableAdapter ta = new DataSet1TableAdapters.UsersTableAdapter();
    DataSet1.UsersDataTable dt = ta.GetData;
    return dt.Rows(0);
}

I get the error Cannot implicitly convert type 'System.Data.DataRow' to 'MyProject.DataSet1.UsersRow'. An explicit conversion exists (are you missing a cast?)

How can I return my strongly typed row in C#

Upvotes: 1

Views: 2478

Answers (3)

peterG
peterG

Reputation: 1641

A more efficient solution would be to add a query to the tableadapter along the lines of SELECT TOP 1 .. . FROM users, (or more generally, add a WHERE clause to return the required row.) That way you are not pulling the entire table back just to retrieve one row.

Upvotes: 0

PHeiberg
PHeiberg

Reputation: 29851

You should be able to get it strongly typed using

dt[0];

Upvotes: 4

SausageFingers
SausageFingers

Reputation: 1846

The solution was to explicitly convert the Rows item as I returned it:

public DataSet1.UsersRow dr()
{
    DataSet1TableAdapters.UsersTableAdapter ta = new DataSet1TableAdapters.UsersTableAdapter();
    DataSet1.UsersDataTable dt = ta.GetData();
    return (DataSet1.UsersRow)dt.Rows(0);
}

Upvotes: 2

Related Questions