【问题标题】:C# - Could anyone help me with a text box?C# - 谁能帮我一个文本框?
【发布时间】:2016-10-23 06:49:16
【问题描述】:

我必须在私有 void 文本框中输入什么才能让用户输入一个金额,该金额将应用于 await Connection.SendToServerAsync(2700, 790);就是现在。所以假设用户在 texbox 中输入 2000, 8,那么 (2700,790) 必须更改为 (2000, 8)

namespace Application
{
    public partial class Form1 : ExtensionForm
    {
        public Form1()
        {
            InitializeComponent();
        }
        private async void button1_Click(object sender, EventArgs e)
        {
            int repeat = 5;

            for (int i = 0; i <= repeat; i++)
            {
                await Connection.SendToServerAsync(2700, 790);
                await Connection.SendToServerAsync(3745);
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

我得到了这个答案:

您可以使用 TextBox.Text 获取文本框的值。 它以字符串形式出现,因此您必须转换为 int。您可以使用以下方法之一执行此操作: 诠释解析 转换.ToInt32 使用转换后的值,您可以在单击按钮时使用新值调用方法。

谁能告诉我它是如何通过复制我的代码来完成的?

【问题讨论】:

  • 对不起,您的问题表明您甚至没有尝试过任何事情并要求我们完成您的工作。您是否尝试致电int.ParseConvertToInt32?显示您尝试了什么

标签: c# winforms


【解决方案1】:

您不需要textBox1_TextChanged() 事件

一种肮脏的方式可能是以下

   private async void button1_Click(object sender, EventArgs e)
    {
        int repeat = 5;

        for (int i = 0; i <= repeat; i++)
        {                
            await Connection.SendToServerAsync(2700, Int32.Parse(textBox1.Text); // <--|use the integer value to which textBox1 value can be cast to
            await Connection.SendToServerAsync(3745);
        }
    }

虽然更稳健的方法是在继续之前检查将 textBox1 值实际转换为整数的可能性:

    private async void button1_Click(object sender, EventArgs e)
    {
        int repeat = 5;
        int amount;

        if (Int32.TryParse(textBox1.Text, out amount)) // <--| go on only if textBox1 input value can be cast into an integer
            for (int i = 0; i <= repeat; i++)
            {                
                await Connection.SendToServerAsync(2700, amount); // <--| use the "amount" integer value read from textBox1
                await Connection.SendToServerAsync(3745);
            }
    }

【讨论】:

  • @Misgracious,你熬过去了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
相关资源
最近更新 更多