0

How do I set the result of my encoding to a TextBox?

string myString;
myString = "Hello World";
byte[] data = Encoding.ASCII.GetBytes(myString);
textBox1.Text = data.ToString();

This displays "System.Byte[]" in the TextBox, but I want to instead show the hex result in the TextBox.

Ryan Kohn
  • 13,079
  • 14
  • 56
  • 81
iboy15
  • 35
  • 1
  • 9
  • 1
    Whoever upvoted the question please explain how OP wants to show byte array. – Alexei Levenkov Sep 16 '14 at 15:58
  • @Alireza: It's not a duplicate - this person wants to show the actual bytes, not the string representation. – Ian Sep 16 '14 at 15:59
  • @Ian: the duplicate question covers all the possible ways to display a `byte[]` as a string, including the actual bytes. – Ryan Kohn Sep 16 '14 at 16:06
  • @Ian the question proposed by Alireza does cover all options in second answer. It is essentially the same as Jon Skeet's (+1) answer here. – Alexei Levenkov Sep 16 '14 at 16:07

3 Answers3

3

You can't set the encoding of a text box, but it sounds like you're just trying to display some binary data in a text box... did you want hex, for example? If so, BitConverter.ToString(byte\[\]) is your friend:

textBox1.Text = BitConverter.ToString(data);

... will give you something like 48-65-6C-6C-6F-20-57-6F-72-6C-64. You can using string.Replace to remove the hyphens if you want, e.g.

textBox1.Text = BitConverter.ToString(data).Replace("-", " ");

There are alternative representations of binary data as text, of course. For example, you could use base64:

textBox1.Text = Convert.ToBase64String(data);

But I suspect hex is what you're after.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Am I correct you're looking for a hex-dumping of your bytes? If yes, try something like this:

textBox1.Text = BitConverter.ToString(data);
Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42
1

To get the string result for the byte[], you can use:

textBox1.Text = Encoding.ASCII.GetString(data)
Ryan Kohn
  • 13,079
  • 14
  • 56
  • 81