ASP Repeater按钮文本更改

3

你好,我希望能够根据 SQL 所选择的值动态更改重复器内按钮的文本。

以下是我的代码:

asp.cs

if (!IsPostBack) 
{
   string getEmp = "Select employeeid, photo, lastname, firstname, departmentname, designation,userType from tblEmployee e inner join tblDepartment d on d.departmentid=e.department";
   SqlCommand com = new SqlCommand(getEmp,con);
   con.Open();
   SqlDataReader dr = com.ExecuteReader();
   Button btnSet = (Button)FindControl("btnSet");
   if (dr.HasRows)
   {
      if (dr.Read())
      {
         if (btnSet != null)
         {
             if (dr["userType"].ToString() == "2")
             {
                btnSet.Text = "Set as Normal User";
             }
             else
             {
                btnSet.Text = "Set as Power User";
             }
         }
      } 
   }
   Repeater1.DataSource = dr;
   Repeater1.DataBind();
   dr.Dispose();
   con.Close();

aspx

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<asp:Button ID="btnSet" commandname="set" commandargument=<%# Eval  ("employeeid") %> runat="server" class="tiny success expand button"  Text="" />


我的代码似乎不起作用。我不知道我在这个问题上是否有正确的方法。虽然我尝试遵循在互联网上找到的几个答案,但没有任何作用。 - user3264955
亲爱的,我给你发送了一个简短有效的解决方案,请查看一下。 - Developerzzz
3个回答

7
您可以订阅Repeater的ItemDataBound事件。它允许您访问项目的控件,并根据当前项目的值进行更改。请查看此处获取更多信息。
private void Repeater1_ItemDatabound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        // Retrieve button of the line
        var btn = e.Item.FindControl("btnSet") as Button;
        if (btn != null)
        {
            // Set text of button based on e.Item.DataItem;
        }
    }
}

5

试试这个,它非常简短且有效。

    <asp:Button ID="btnSet" commandname="set" commandargument=<%# Eval("employeeid") %> runat="server" class="tiny success expand button"  Text='<%# Eval("userType").ToString() == "2" ?"Set as Normal User" : "Set as Power User" %>' />

如果您需要更多帮助,请告诉我。


哦我的天,这真的有效。虽然我还没有尝试过其他在这里发布的解决方案。感谢大家的帮助。我会尝试理解你们给出的答案。 - user3264955
好的亲爱的,现在请把它作为我的答案,并加上+1。 - Developerzzz
我在这里是一个完全的新手。第一次发布问题。它说我需要至少15个声望才能+1 =[ - user3264955
没关系亲爱的,我拿到了我的分数,谢谢亲爱的。如果你需要任何关于 .net 和数据库方面的帮助,请联系我 :D - Developerzzz
当你获得15分时,你可以给亲爱的人+1。 - Developerzzz

1
你需要在重复器的databind事件中使用它。类似这样:

例如:

 void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) 
 {
      // Execute the following logic for Items and Alternating Items.
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {

        Button btnSet = (Button)e.Item.FindControl("btnSet");
        if ( e.Item.DataItem["userType"].ToString() == "2")
        {
          btnSet.Text = "Set as Normal User";
        }
        else
        {
          btnSet.Text = "Set as Power User";
        }

      }
   }    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接