如何对转发器内的按钮单击事件进行编程

时间:2019-04-06 05:10:30

标签: c# html asp.net

我是ASP.NET的新手。我在中继器内添加了一个按钮。当theruser单击按钮时,特定行值应显示在转发器外部的标签上。这是我要实现的设计。

enter image description here

中继器:

<asp:Repeater ID="rpt3" runat="server">
    <ItemTemplate>  
<h3>   <%#Eval("name") %>  </h3>
<asp:Button ID="Button1" runat="server" Text="Show Details"/> 
    </ItemTemplate>
</asp:Repeater>

<asp:Label ID="Label1" runat="server" ></asp:Label>

C#:

public void Getuser() {
    using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) {
        SqlCommand cmd = new SqlCommand("select name from message  where emailid= '" + Session["un"].ToString() + "'", con);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        con.Open();
        da.Fill(dt);
        if (dt.Rows.Count > 0 && dt.Rows[0][0] != string.Empty) {
            rpt3.DataSource = dt;
            rpt3.DataBind();
        } else {
            rpt3.DataSource = null;
            rpt3.DataBind();
        }
        con.Close();
    }
}

1 个答案:

答案 0 :(得分:1)

有很多方法,您可以在页面加载时添加点击事件。只需检查转发器中的项目并设置按钮单击事件,如:

foreach (RepeaterItem rptItem in rpt3.Items)
     {
         Button btn = rptItem .FindControl("btnShowLabel") as Button;
         btn.Click += new EventHandler(btn_Click);
     }

然后您可以在点击事件上执行任务,例如:

void btn_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        RepeaterItem rptItem = (RepeaterItem)btn.NamingContainer;
        Label lb = (Label)rptItem.FindControl("lbShowing");
        lb.Text = "Showing you text here";
    }
  1. 也可以在按钮上单击“命令名称”,然后是转发器ItemCommand事件。

后面的代码:

 protected void rp3_ItemCommand(object source, RepeaterCommandEventArgs e)
  {
    if (e.CommandName == "show")
    {
    }
  }

正面      

相关问题