Bala murugan
Bala murugan

Reputation: 45

how to convert sqlcommand type to String type

I am trying to fetch value from the first row and first column. After fetching I need to convert that value to a string. Please help me with the conversion.

Here is my current code:

conn.ConnectionString = "Server=localhost;Database=MIN-MAK MRO;Trusted_Connection=true";
conn.Open();

SqlCommand command = new SqlCommand("SELECT Top 1 FirstName FROM HistoryReport ", conn);

Upvotes: 0

Views: 2457

Answers (2)

Nyerguds
Nyerguds

Reputation: 5629

The result from a query with a single result is returned as bare Object. To safely convert it to string, you need to first check it against both DBNull.Value and against null, before performing ToString() on it.

public static String SafeGetString(Object databaseResult)
{
    if (databaseResult == DBNull.Value || databaseResult == null)
        return null;
    return databaseResult.ToString();
}

Upvotes: 0

Abhishek
Abhishek

Reputation: 2490

Something like this -

string getValue = command.ExecuteScalar().ToString();

Note: If there are no rows .ExecuteScalar() will return null

Upvotes: 1

Related Questions