如何在C# For循环中使用用户输入变量控制循环次数
修改后的代码
private void Button1_Click(object sender, EventArgs e) { string x = "^XA^FO70,0^FS^FX Third section with bar code.^BY2,3,50^FO5,90^BC^FD123456789456744^FS^FX Fourth section(the two boxes on the 24bottom).^FO10,162^GB222,30,3^FS^CF0,20^FO15,170^FDREF:11905-01^FS^FO150,170^FDTALLA:24^FS^CF0,190^XZ"; PrintDialog pd = new PrintDialog(); pd.PrinterSettings = new PrinterSettings(); pd.ShowDialog(this); // 获取TextBox输入,这里假设控件名为txtRepeatCount,根据实际名称替换 string input = txtRepeatCount.Text.Trim(); int repeatCount; // 验证输入是否为有效正整数 if (int.TryParse(input, out repeatCount) && repeatCount > 0) { // 根据用户输入的次数执行循环 for (int i = 0; i < repeatCount; i++) { RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, x); } } else { // 输入无效时提示用户 MessageBox.Show("请输入一个大于0的有效数字"); } }
关键改动说明
- 读取用户输入:从TextBox控件获取文本,先通过
Trim()去除前后空格,避免空字符或空格导致解析失败。 - 安全验证输入:用
int.TryParse解析输入,避免用户输入非数字内容时抛出异常,同时限制数字必须大于0,防止无效循环次数。 - 动态循环逻辑:把原代码中固定的循环条件
es1 < 5替换为i < repeatCount,循环次数完全由用户输入的数字决定。 - 错误提示:添加输入无效时的弹窗提示,提升用户体验。
注意:如果你的TextBox控件名称不是
txtRepeatCount,请替换成你实际使用的控件名称。
内容的提问来源于stack exchange,提问作者Andres Martinez
相关产品推荐
相关产品推荐

