Raven Dreamer Raven Dreamer - 4 years ago 142
SQL Question

What do C# Table Adapters actually return?

stack overflow !

I'm working on an application that manipulates SQL tables in a windows form application. Up until now, I've only been using the pre-generated Fill queries, and self-made update and delete queries (which return nothing).

I am interested in storing the value of a single value from a single column (an 'nchar(15)' name), and though I have easily written the SQL code to return that value to the application, I have no idea what it will be returned as.

SELECT [Contact First Name] FROM ContactSkillSet
WHERE [Contact ID] = @CurrentID


Can the result be stored directly as a string? Do I need to cast it? Invoke a toString method?

Thanks!

Edit: Interestingly enough, the following works:

String firstName = this.contactSkillSetTableAdapter.GrabFirstName(userKey);


The joys of the Visual Studio data wizard, I suppose.

Answer Source

A TableAdapter is used to fill a DataTable. The result of your example query will still be a DataTable but with a single column in a single row. You can get the value using:

var adapter = new SomeKindOfTableAdapter();
var dataTable = new DataTable();

adapter.Fill(dataTable);

string contactFirstName = (string)dataTable.Rows[0][0];

There are other ways to get your value without using a Table Adapter though:

string query = @"SELECT [Contact First Name] 
                FROM ContactSkillSet 
                WHERE [Contact ID] = @Current";

string result;

using(SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();

    using(SqlCommand command = new SqlCommand(query, conn))
    {
        result = (string)command.ExecuteScalar();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download