0

当我在做一个预订系统时,我在我的网页中实现了几个按钮。我设法限制用户点击我网页中的按钮,但我的问题是用户现在甚至无法选择一个按钮,因为当他们尝试点击第一个按钮时,我的警报消息会弹出,要求他们只选择一个按钮。我如何允许用户只选择一个按钮,当他们尝试选择另一个按钮时,我的警报消息将开始使用。我怀疑这是我造成问题的原因。

这是我的 .cs 代码:

protected void Button1_Click(object sender, EventArgs e)
{
    int counter = 0;
    if (counter > 1)
    {
        Button1.Text = "Selected";
        Button1.BackColor = System.Drawing.Color.DarkGreen;
        Button2.Text = "Selected";
        Button2.BackColor = System.Drawing.Color.DarkGreen;
        startingTime.Text = "9AM";
        endingTime.Text = "11AM";
    }

    else
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
    }
}
protected void Button2_Click(object sender, EventArgs e)
{
    int counter = 1;
    if (counter > 0)
    {
        Button2.Text = "Selected";
        Button2.BackColor = System.Drawing.Color.DarkGreen;
        Button3.Text = "Selected";
        Button3.BackColor = System.Drawing.Color.DarkGreen;
        startingTime.Text = "10AM";
        endingTime.Text = "12PM";

    }

    else
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
    }
}
protected void Button3_Click(object sender, EventArgs e)
{
    int counter = 1;
    if (counter > 0)
    {
        Button3.Text = "Selected";
        Button3.BackColor = System.Drawing.Color.DarkGreen;
        startingTime.Text = "11AM";
        endingTime.Text = "1PM";

    }

    else
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
    }
}
4

3 回答 3

3

这将始终评估为false,因此您始终会进入else块:

int counter = 0;
if (counter > 1)

您应该在代码执行counter 后进行更改,它也应该是您的类的一个字段(否则对它的任何更改都会丢失,因为counter一旦方法退出,当前就消失了)。

您还可以使用Button.Enabled启用/禁用按钮。

于 2012-07-25T09:23:52.807 回答
1

声明int counter = 0为全局变量。

于 2012-07-25T09:27:07.733 回答
0

您必须尝试对 Button1 使用此示例

//Save your counter in Viewstate or InputHidden in order to persist

public int Counter 
{
    get
    {
        int s = (int)ViewState["Counter"];
        return (s == null) ? 0 : s;
    }
    set
    {
        ViewState["Counter"] = value;
    }
}


protected void Button1_Click(object sender, EventArgs e)
{
    Counter = Counter + 1;

    if (Counter > 1)
    {
        Button1.Text = "Selected";
        Button1.BackColor = System.Drawing.Color.DarkGreen;
        Button2.Text = "Selected";
        Button2.BackColor = System.Drawing.Color.DarkGreen;
        startingTime.Text = "9AM";
        endingTime.Text = "11AM";
    }

    else
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please select one slot only');", true);
    }
}
于 2012-07-25T09:28:34.757 回答