Reputation: 23
I'm making a decimal to HEX converter. The decimal number is typed into a textbox by the user and there are 8 comboboxes, one for each possible digit. The method i have written takes the input string from the textbox and converts the decimal number to hexadecimal and returns it as a string.
How can I put the returned string (hex number) into the correct comboboxes from "cboHex0" to "cboHex7", going from least significant bit to MSB.
Tried this but it does not work. Appreciate all help as I am new to stackoverflow and C#.
void decimalToHex(long dec)
{
if ((dec < 1) || (dec > 4294967295))
//if ((dec < 1) || (dec > 4294967295))
{
MessageBox.Show("ERROR\r\n" +
"Decimal number is not within the range for conversion");
return "0";
}
long hex = dec;
string hexStr = string.Empty;
while (dec > 0)
{
hex = dec % 16;
if (hex < 10)
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 48).ToString());
else
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 55).ToString());
dec /= 16;
}
//return hexStr;
//splitte streng til array.
string[] stringElements = hexStr.Split('');
stringElements.Reverse();
if (stringElements.Length > 0)
{
cboHex0.Text = stringElements[0];
}
if (stringElements.Length > 1)
{
cboHex1.Text = stringElements[1];
}
if (stringElements.Length > 2)
{
cboHex2.Text = stringElements[2];
}
if (stringElements.Length > 3)
{
cboHex3.Text = stringElements[3];
}
if (stringElements.Length > 4)
{
cboHex4.Text = stringElements[4];
}
if (stringElements.Length > 5)
{
cboHex5.Text = stringElements[5];
}
if (stringElements.Length > 6)
{
cboHex6.Text = stringElements[6];
}
if (stringElements.Length > 7)
{
cboHex7.Text = stringElements[7];
}
}
Edit: Okay so seems that I can target a character from a string by stringName[index].
So if the returned string is "1AF", how can I code so that the 8 comboboxes will show 0 , 0 , 0 , 0 , 0 , 1 , A , F ?
Upvotes: 2
Views: 75
Reputation: 4163
First, to make the work easier, make your result a consistent length:
hexStr = hexStr.PadLeft(8, '0');
Then, you can simply assign the boxes as follows:
cboHex0.Text = hexStr.Substring(0,1);
cboHex1.Text = hexStr.Substring(1,1)
cboHex2.Text = hexStr.Substring(2,1);
etc.
Upvotes: 3