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="" />

4

3 回答 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;
        }
    }
}
于 2014-02-03T08:04:04.213 回答
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" %>' />

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

于 2014-02-03T08:07:52.483 回答
1

您必须使用中继器的数据绑定事件。

就像是:

 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";
        }

      }
   }    
于 2014-02-03T08:06:04.063 回答