[英]C# splitting string into comboboxes
我正在將十進制轉換為十六進制轉換器。 十進制數字由用戶輸入到一個文本框中,有 8 個組合框,每個可能的數字一個。 我編寫的方法從文本框中獲取輸入字符串並將十進制數轉換為十六進制並將其作為字符串返回。
如何將返回的字符串(十六進制數)放入從“cboHex0”到“cboHex7”的正確組合框中,從最低有效位到 MSB。
試過這個,但它不起作用。 感謝所有幫助,因為我是 stackoverflow 和 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];
}
}
編輯:好的,看來我可以通過stringName [index]從字符串中定位一個字符。
因此,如果返回的字符串是“1AF”,我該如何編碼以使 8 個組合框顯示 0、0、0、0、0、1、A、F?
首先,為了使工作更容易,使您的結果長度一致:
hexStr = hexStr.PadLeft(8, '0');
然后,您可以簡單地分配框,如下所示:
cboHex0.Text = hexStr.Substring(0,1);
cboHex1.Text = hexStr.Substring(1,1)
cboHex2.Text = hexStr.Substring(2,1);
等等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.