简体   繁体   English

回发后,动态按钮将不保留值

[英]Dynamic Buttons won't hold value after Post Back

I have buttons that display dynamically when the page loads. 我有在页面加载时动态显示的按钮。 What is suppose to do is: 应该做的是:

  1. Click a dynamic button, displays to a text box 单击动态按钮,显示到文本框
  2. Click Issue Ticket 点击发行票
  3. Print Ticket 1. 打印票1。

If I click on the next dynamic button it should go thru the same process and it should print Ticket 2. 如果我单击下一个动态按钮,则应按相同的过程进行,并应打印故障单2。

The issue is that is not incrementing in value. 问题是价值没有增加。 I believe is because the page postback everytime I click the Issue Ticket therefore resetting the ticket value back to 1. Anyway to go around this. 我相信是因为每次我单击“发行工单”时页面都会回发,因此将工单值重置为1。无论如何要解决此问题。

int ticket = 0;    

protected void Page_Load(object sender, EventArgs e)
{
      string buttonName;
      try
      {

         btnIssueTicket.Enabled = false;
         using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectString"].ConnectionString))
           {
                connStr.Open();
                SqlCommand select = new SqlCommand("SELECT TransTypeId, TransTypeDesc from tblTransType", connStr);
                SqlDataReader reader = select.ExecuteReader();

                //Reads all records 
                while (reader.Read())
                {
                    transID = Convert.ToInt32(reader["TransTypeId"].ToString());
                    buttonName = reader["TransTypeDesc"].ToString();

                    CreateButton(buttonName);
                }

                connStr.Close();
                reader.Close();

            }
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Error: " + ex.Message.ToString();
        }

    } 
}

 //Buttons properties. Creates buttons dynamically inside the Layout Panel
    private void CreateButton(string buttonName)
    {


        transbutton = new Button();

        transbutton.Text = buttonName;
        transbutton.ID = transID.ToString();
        transbutton.CssClass = "transButtons";  //CSS property for buttons        
        transbutton.Click += new EventHandler(transbutton_Click); //Event Handler for dynamic buttons
        panelButtons.Controls.Add(transbutton); //Adds button to Layout Panel

    }

    //When Dynamic buttons clicked.
    private void transbutton_Click(object sender, EventArgs e)
    {  
        //Displays Transactions in TextBox
        tbList.Text += ((Button)sender).Text + "\r\n";
        btnIssueTicket.Enabled = true;
        lblStatus.Text = "";                   
    }

   protected void btnIssueTicket_Click(object sender, EventArgs e)
    {

         tbPrint.Text = ticket + 1;
    }

You need to have ID for a control if it is created dynamically. 如果控件是动态创建的,则需要具有该控件的ID。

Otherwise, they will become null when the page is posted back to server. 否则,当页面回发到服务器时,它们将为null。

rotected void Page_Load(object sender, EventArgs e)
{
   string buttonName;
   try
   {   
      ...
      CreateButton(transID, buttonName); // Pass transID          
      ...
   } 
}

private void CreateButton(int transID, string buttonName)
{
  transbutton = new Button();
  transbutton.Text = buttonName;
  transbutton.ID = transID.ToString(); // ID is required
  ...
}

Besides, if you want to keep track the number of tickets, you need to save it in ViewState to persist the data. 此外,如果要跟踪票证数量,则需要将其保存在ViewState以保留数据。

public int Ticket
{
    get { return Convert.ToInt32(ViewState["Ticket"] ?? 0); }
    set { ViewState["Ticket"] = value; }
}

// Usage
protected void btnIssueTicket_Click(object sender, EventArgs e)
{
     Ticket++;
     tbPrint.Text = Ticket.ToString();
}

When you declare a variable inside your page class, it is initialized to its value every time a request hits the server. 当您在页面类中声明变量时,每次请求到达服务器时,该变量都会初始化为其值。

So each time, your ticket value is initialized to 0 . 因此,每次您的ticket值都会初始化为0

If you want to keep this value over multiple requests, you should use the ViewState and keep that value in it. 如果要在多个请求中保留此值,则应使用ViewState并将其保留在其中。

The ViewState will be rendered as a hidden field and sent back to the server at every postback, and you'll be able to keep the precedent value. ViewState将呈现为隐藏字段,并在每次回发时发送回服务器,您将能够保留先前的值。

To have a better understanding of which values are kept and which are lost, take a look at the asp.Net page lifecycle: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.80).aspx 为了更好地了解保留哪些值和丢失哪些值,请查看asp.Net页面生命周期: http : //msdn.microsoft.com/zh-cn/library/ms178472( v=vs.80 ) .aspx

and also there is a very complete description of the viewstate here: http://msdn.microsoft.com/en-us/library/ms972976.aspx 而且这里的viewstate也有非常完整的描述: http : //msdn.microsoft.com/zh-cn/library/ms972976.aspx

and also here: http://www.codeproject.com/Articles/31344/Beginner-s-Guide-To-View-State 也是这里: http : //www.codeproject.com/Articles/31344/Beginner-s-Guide-To-View-State

Since you having integer value as tbPrint.Text You can do as below 由于您具有整数值作为tbPrint.Text您可以执行以下操作

Set initial tbPrint.Text 1 and 设置初始tbPrint.Text 1和

int no;
if (int.TryParse(tbPrint.Text, out no))
{
    tbPrint.Text = no + 1;
}

Otherwise You can use Session, Viewstate, or a hidden field. 否则,您可以使用Session,Viewstate或隐藏字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM