如何在 C# 中自动递增数字?
我正在使用 C# 2008 Windows 窗体应用程序。
在我的项目中,有一个 TextBox 控件,我想为样本 s00 自动生成数字,接下来当我再次返回表单时,它应该像 s01、s02、s03 这样递增... ...就像这样
请帮助我
I am using C# 2008 Windows Forms application.
In my project there is a TextBox
control and in that I want make an auto generate numbers for samples s00, next when I come back to form again it should be increment like s01,s02,s03......like that
Please help me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
很容易。保留一个变量来保留当前数字。
然后单击按钮,生成数字字符串,如下所示:
Quite easy. Keep a variable to keep the current number.
Then on click of button, generate the number string like this:
按照Øyvind Knobloch-Bråthen的建议进行操作,但如果您希望在表单停用和激活时自动完成>(你回到表单并给予它焦点)然后你可以做这样的事情。
只有当您确定框中的文本始终采用上述格式时,此方法才有效
Do as suggested by Øyvind Knobloch-Bråthen but if you want it to be done automatically when form is Deactivated and Activated (You come back to the form and give it focus) then you can do somthing like this.
This only works if you are sure the text in box will always be in the mentioned format
正如 Øyvind Knobloch-Bråthen 所说:使用变量跟踪整数。只有您应该像这样格式化它(Microsoft 首选):
或者如果您想用一行少的代码来完成它:
请参阅 MSDN 有关格式化整数的完整参考。
Just as Øyvind Knobloch-Bråthen said: Keep track of the integer using a variable. Only you should format it like this (Microsoft preferred):
Or if you want to do it with one line less code:
See MSDN for a complete reference for formatting integers.
上面的 oyvind-knobloch-brathen 的稍微好一点的变体:
//s00、s01、s02。如果您想要范围 0001-9999,只需将“00”更改为“0000”等即可。
A slightly better variation of oyvind-knobloch-brathen's above:
//s00, s01, s02. If you want, say, the range 0001-9999, just change "00" to "0000", etc.
如果字符串的文本部分未知(字符串末尾有或没有数字),此函数的变体可能会有所帮助:
If the text component of the string is unknown (with or without a number at the end of the string), variations of this function may be helpful:
试试这个对于数字的自动生成和数字的自动增量:
Try This For auto generation of number and auto incrementation of number:
另一种单行方法是:
其中 counter 定义如下:
Another single line approach would be:
Where counter defines like this:
这是 C# 中生成自动递增 id 的解决方案,不需要增加或执行任何操作。它会起作用的。每当一个新对象创建时,它的值就会增加 1。
This is the solution to generator auto incremented id in C# which don't need to increase or do anything. It will just work. whenever a new object created its value will increase by 1.
if (dt.Rows[0]["Column_name'"].ToString() == null) { Label1.Text = "DMBP-000001"; } else{ Label.Text= dt.Rows[0]["Column_name'"].ToString(); } } 抓住 { } }
if (dt.Rows[0][" Column_name'"].ToString() == null) { Label1.Text = "DMBP-000001"; } else{ Label.Text= dt.Rows[0][" Column_name'"].ToString(); } } catch { } }