按钮事件处理程序不起作用

时间:2013-12-01 14:55:48

标签: c# asp.net

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

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#。有人可以帮我吗 ?感谢。

1 个答案:

答案 0 :(得分:-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());
}