Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert a Byte Array to String for a DataGridView

I have a Domain Class User with the Following properties (Fields):

UserId (int)
UserName (nvarchar(25))
SecurePassword (varbinary(32))
Salt (varbinary(32))

SecurePassword and Salt store a byte array with a length of 32 as you may have guessed. If I set my

BindingSource.DataSource = context.Users.Local.ToBindingList();

And then my

DataGridView.DataSource = BindingSource;

I’ll get an Error telling me to Handle the DataError Event for the GridView. Once I do that with an empty method the SecurePassword and Salt Columns show [X] for every row.

Now, I could use linq to render that in an anonymous type as:

 var data = from u in context.Users
            select new
            {
                u.UserId,
                u.UserName,
                SecurePassword = BitConverter.ToString(u.SecurePassword),
                Salt = BitConverter.ToString(u.Salt)
            };

But I really don’t want an anonymous type. In WPF I could have written a Converter that inherits from IValueConverter, but that doesn’t seem to be available in WinForms. Any help would be greatly appreciated and welcomed.

like image 817
Randy Avatar asked Oct 19 '25 14:10

Randy


2 Answers

Use CellFormatting event. Something like:

void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // 2 - Salt, 3 - SecurePassword
    if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
    {
        if (e.Value != null)
        {
            byte[] array = (byte[])e.Value;
            e.Value = BitConverter.ToString(array);
            e.FormattingApplied = true;
        }
        else
            e.FormattingApplied = false;
    }
}
like image 98
Alexander Petrov Avatar answered Oct 21 '25 04:10

Alexander Petrov


To build upon the other answer, the simplest way I achieved this was:

  1. Go into Properties of your DataGridView, find the Columns property, edit it, and change the ColumnType of your binary columns to DataGridViewTextBoxColumn.
  2. Go into the Events pane and generate a method on the CellFormatting event.
  3. Set the code of the method to be something like:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 1 || e.ColumnIndex == 2)
    {
        if (e.Value != null)
        {
            e.Value = Encoding.UTF8.GetString((byte[]) e.Value);
            e.FormattingApplied = true;
        }
        else
            e.FormattingApplied = false;
    }
}
like image 35
Coxy Avatar answered Oct 21 '25 05:10

Coxy