一个非常没有经验的程序员的简单问题

时间:2011-01-21 20:33:53

标签: c#

简单问题:这是我创建的方法

public void move()
{
    double radians = direction * Math.PI / 180;
    //change the x location by the x vector of the speed
    X_Coordinate += (int)(speed * Math.Cos(radians));

    //change the y location by the y vectior of the speed
    Y_Coordinate -= (int)(speed * Math.Sin(radians));
}

如何将值输入文本框,使用名为move的按钮调用此方法并显示结果?

3 个答案:

答案 0 :(得分:1)

http://www.asp.net/general/videos/intro-to-aspnet-controls上查看ASP.Net上的视频教程,了解有关asp.net控件的介绍。它将帮助您定义带有事件的按钮。

答案 1 :(得分:1)

如果您正在使用Visual Studio,那么......

打开设计器,然后从工具箱中将TextBoxButton拖到页面上(以及您需要的任何其他TextBox项目,我假设您已经拥有他们从现在开始。 双击刚刚放置在页面上的按钮。这将创建一个事件处理程序,当单击该按钮时,将执行此块范围内的代码。 将以下代码放在生成的事件处理程序代码块中,并进行适当更改(例如TextBox名称(您可以使用VS中的Property Explorer更改这些名称)):

var direction = 0;
if (int.TryParse(DirectionTextBox.Text, out direction))
{
    //further validate input here, as necessary

    Move(direction);
    XTextBox.Text = X_Coordinate.ToString();
    YTextBox.Text = Y_Coordinate.ToString();
}
else
{
    //handle invalid input, if not already done elsewhere.
}

据推测,此处X_CoordinateY_Coordinate是可访问的变量。所以,现在,改变你的move方法来接受一个参数,如下所示:

public void Move(int direction)
{
    double radians = direction * Math.PI / 180;
    //change the x location by the x vector of the speed
    X_Coordinate += (int)(speed * Math.Cos(radians));

    //change the y location by the y vectior of the speed
    Y_Coordinate -= (int)(speed * Math.Sin(radians));
}

请注意,到目前为止,我不知道您希望将Move方法的哪些元素作为变量输入,但我会继续思考这个想法可以扩展为as你喜欢/需要的许多元素。另请注意,还有很多其他方法可以解决这个问题 - 我的建议是足够整洁(根据我们提供的信息)并且与您最初发布的代码相比没有太大的改变,因此,希望您更容易实现;但是你可以从这个方法返回一个复合类型,并使用直接返回的结果设置视觉输出,以使事情更简洁。

答案 2 :(得分:0)

连接按钮的Click事件,在事件处理程序中,您可以通过TextBoxName.Text访问输入的值。您可能需要使用int.Parse解析字符串值,以便在计算中使用它。

您的按钮看起来像这样。

<asp:Button ID="MoveBtn" runat="server" onclick="Move" Text="Move" />

然后在你的代码中

protected void Move(object sender, EventArgs e)
{
   // Call your move method here.
   // If it is in the same class, it's just move();
   // Otherwise you need a reference to your class so you can call it.
}