views:

730

answers:

2

I have a database field whose dataType is varBinary. Now in a gridView I want to display that data. But i am getting output:

System.Byte[]

not the value

0x2C6D1A

which is in the database.

Please help how to solve this problem.

+2  A: 

You can use the BitConverter class to format your byte array for display purposes:

string forDisplay =
    "0x" + BitConverter.ToString(yourByteArray).Replace("-", string.Empty);

If you don't want to convert directly to a string, then BitConverter has a load of methods for converting from byte arrays to various other types.

EDIT...

If you're binding some query results directly to the GridView control then it might be easier to convert your VARBINARY column to a VARCHAR in the query itself:

SELECT CONVERT(VARCHAR(MAX), your_varbinary_column, 1) AS for_display
FROM your_table

(Note: This type of conversion - from VARBINARY to VARCHAR in '0x1234AB' format - only works correctly in SQL Server 2008. Earlier versions of SQL Server just cast the binary data directly to character data.)

LukeH
A: 

If there isn't anything obvious available, perhaps just loop:

    public static string ToHexString(byte[] raw)
    { // could also be an extension method
        StringBuilder sb = new StringBuilder("0x", 2 + (raw.Length * 2));
        for (int i = 0; i < raw.Length; i++)
        {
            sb.Append(raw[i].ToString("X2"));
        }
        return sb.ToString();
    }

If this is a class property, it would be trivial to create a TypeConverter that does this (for display purposes), and mark the property with [TypeConverter(typeof(HexConverter))]:

    class HexConverter : TypeConverter // untested
    {
        public override object ConvertTo(ITypeDescriptorContext context,
            System.Globalization.CultureInfo culture,
            object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return ToHexString((byte[])value);
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
Marc Gravell