Windows Forms: Convert string to binary in C#

This tutorial shows you how to convert a string to binary in C#.NET Windows Forms Application.

To convert string to binary in c#, you can drag the textbox, label and button from your visual studio toolbox to your winform, then layout your UI as shown below.

convert string to binary in c#

Next, Create the StringToBinary method allow you to convert text to binary as the following c# code.

public string StringToBinary(string data)
{
    StringBuilder sb = new StringBuilder();
    foreach (char c in data.ToCharArray())
        sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
    return sb.ToString();
}

Finally, Add code to handle the Convert button click event.

private void btnConvert_Click(object sender, EventArgs e)
{
    txtOutput.Text = StringToBinary(txtInput.Text);
}

Press F5 to build and run your project, then you can enter a string and convert to binary sequence in c#.