String.Format中数字的动态长度 [英] Dynamic length of a number in a String.Format
问题描述
大家好
我有一段代码来创建具有4个变量的文档编号.
前缀,后缀,NextNum和长度.
前三个很简单.在过去的第四版中,我已经进行了硬编码,但现在需要改进.一个答案是使用switch语句使用用户可能选择的几个选项之一,但这似乎是不好的编码.
代码:
Hi All
I have a piece of code to create document numbers featuring, 4 variables.
Prefix, Suffix, NextNum and Length.
The first 3 are rather simple. In the past the 4th one I have hard coded but now it needs improvement. One answer is to use a switch statement to use one of a few options the user may have selected but that seems like bad coding.
Code:
list = fa.SelectList("select Prefix, Suffix, NextNum, Length from docnumbers where Form = 'Invoice' limit 1", list);
t0.Text = String.Format("{0}{2:000000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]), list[3][0]);
我已经硬编码必须显示6个字符,但是现在我希望它从数据库中的Length变量中获取.
有什么想法吗?
非常感谢
安德鲁
开关看起来像
I have hardcoded that 6 characters must be displayed but now I want it to get it from the Length variable in the database.
Any ideas?
Many thanks
Andrew
Switch would look like
list = fa.SelectList("select Prefix, Suffix, NextNum, Length from docnumbers where Form = 'Invoice' limit 1", list);
switch (list[3][0])
{
case 1:
t0.Text = String.Format("{0}{2:0}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 2:
t0.Text = String.Format("{0}{2:00}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 3:
t0.Text = String.Format("{0}{2:000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 4:
t0.Text = String.Format("{0}{2:0000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 5:
t0.Text = String.Format("{0}{2:00000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 6:
t0.Text = String.Format("{0}{2:000000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 7:
t0.Text = String.Format("{0}{2:0000000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 8:
t0.Text = String.Format("{0}{2:00000000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 9:
t0.Text = String.Format("{0}{2:000000000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
case 10:
t0.Text = String.Format("{0}{2:0000000000}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
default:
t0.Text = String.Format("{0}{2}{1}", list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
break;
}
推荐答案
您可以创建一个字符串变量并使用它:
You could create a string variable and use it:
string zeroes = new string(''0'', (list[3][0]));
string testFormat = "{0}{2:" + zeroes + "}{1}";
tx0.Text = String.Format(testFormat, list[0][0], list[1][0], Convert.ToInt32(list[2][0]));
这篇关于String.Format中数字的动态长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!