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.
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;
}
}
To build upon the other answer, the simplest way I achieved this was:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With