【问题标题】:Button Event Handler Not Working按钮事件处理程序不起作用
【发布时间】:2013-12-02 00:07:26
【问题描述】:

我在C# 中为button 使用以下代码行:

void reserve_click(object sender, EventArgs e)
{
   string req = ((Button)sender).ID;
}

 protected void Button2_Click(object sender, EventArgs e)
        {
            issuedBooks.Visible = false;
            search.Visible = true;
            string text = TextBox1.Text;
            string selectCommand = "SELECT id, title, author FROM book WHERE title LIKE '%" + text + "%' OR author LIKE '%" + text + "%'";
            string conString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            SqlDataAdapter dad = new SqlDataAdapter(selectCommand, conString);
            DataTable dtblCategories = new DataTable();
            dad.Fill(dtblCategories);
            DataView view = new DataView(dtblCategories);



            foreach (DataRowView row in view)
            {
                TableRow newrow = new TableRow();
                TableCell newcell1 = new TableCell();
                TableCell newcell2 = new TableCell();
                TableCell newcell3 = new TableCell();    
                newcell1.Text = row["title"].ToString();
                newrow.Cells.Add(newcell1);
                newcell2.Text = row["author"].ToString();
                newrow.Cells.Add(newcell2);

                string book_id = row["id"].ToString();

                Button btn = new Button();
                btn.ID = "Button_1" + book_id;
                btn.Text = "Reserve";
                btn.Click += new EventHandler(reserve_click);

                newcell3.Controls.Add(btn);
                newrow.Cells.Add(newcell3);

                search.Rows.Add(newrow);

             }

我在表格单元格的动态添加按钮中使​​用上述代码。但上述EventHandler 不起作用或被解雇。我第一次使用asp.netC#。有人可以帮我吗 ?谢谢。

【问题讨论】:

  • 您能告诉我们reserve_click 的代码以及您将其添加到表单的哪个位置吗?
  • 再次检查问题
  • "但是上面的 EventHandler 没有工作或者被解雇了。" - 正在发生什么
  • 我添加了一个断点。它无法到达那里。单击按钮时.. EventHandler 不起作用。
  • 大多数像这样的奇怪案例都是由 OP 的一个非常隐蔽的错误引起的,它们以一种非常无辜的方式使其他人感到困惑。

标签: c# asp.net


【解决方案1】:

这就是答案。试试吧

Page_Load()
{
   Button b = new Button();
   b.ID = topic.Topic_Id + "_1"; // topic_Id is my unique ID for each topic on the blog
   b.Text = "Edit";
   b.ToolTip = "Edit";
   b.CommandArgument = b.ID; //passing this to event handler
   b.Command += new CommandEventHandler(b_Command); //handler
}
void b_Command(object sender, CommandEventArgs e)
{
    System.Windows.Forms.MessageBox.Show(e.CommandArgument.ToString());
}

【讨论】:

  • 您将其添加到 page_load 事件中,但我的是在另一个按钮单击事件处理程序中实现的。
猜你喜欢
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多