Question

I'm writing a tiny hex viewer for my own needs. Stuck in a situation where the standard Label control won't show up an unprintable characters in string:

public string ToASCIIstring(int numColumns)
{
    string ret = String.Empty;
    int stringBegin = 0;

    for (int i = 0; i < Data.Length; i++)
    {
        int colNum = i % numColumns;

        if ((colNum + 1 == numColumns) || (i == Data.Length -1 ))
        {
            ret += Encoding.ASCII.GetString(Data, stringBegin, colNum);
            stringBegin = i + 1;
            ret += "\n";
        }
    }

    return ret;
}

This method returns the correct ASCII string, but after assigning it to the Label.Text property it becomes just an Empty string and nothing is displayed.

Any help on that would be lovely

P.S. I know the code is awful, but it's never gonna see the production, it's just my own analysis tool

Was it helpful?

Solution

I cannot reproduce you problem.

I created a new Windows Forms application using .NET Framework 4.5, and I put one Label on the form. I then have the following code:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    string s = ((char)7).ToString();

    this.label1.Text = s;

    Debug.Assert(this.label1.Text == s);
}

As expected, it runs just fine. Using the default font, this displays a thin bullet.

My guess is that something else is going wrong that has nothing to do with non-printable ASCII characters.

UPDATE: However, the Windows API's behind the label use null-terminated strings, meaning that a zero byte will be interpreted as the end of the string. So the following program fails:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    var bytes = new byte[] { 7, 0, 0x6c, 0 };

    string s = Encoding.ASCII.GetString(bytes);

    this.label1.Text = s;

    Debug.Assert(this.label1.Text == s);
}

After the assignment, the Label.Text property contains a string of length 1, only containing the character with ASCII code 7.

But this works:

    var bytes = new byte[] { 7, 0, 0x6c, 0 };

    string s = Encoding.ASCII.GetString(bytes).Replace((char)0, '.');

    this.label1.Text = s;

    Debug.Assert(this.label1.Text == s);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top