日期:2014-05-18  浏览次数:20450 次

datalist数据绑定是时遇到的问题
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
  {
  Repeater Repeater1;  
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
  int liuyanid = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "id"));
  Repeater1 = e.Item.FindControl("Repeater1") as Repeater;
  dv = NoticesManage.getreplybyliuyan(liuyanid).Tables[0].DefaultView;
  Repeater1.DataSource = dv;
  Repeater1.DataBind();
  }  
  }
请问这句话是干吗的?加与不加有什么区别?
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

------解决方案--------------------
就是判断当前行是ItemTemplate或者AlternatingItemTemplate里面的内容

因为还有SelectedItem,EditItem等。

参见
http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.listitemtype.aspx


执行下面的代码,你就明白这些判断的含义了
HTML code
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  
  protected void Page_Load(object sender, EventArgs e)
  {
    DataList1.DataSource = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
    DataList1.DataBind();
  }

  protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
  {
    //只有加判断,下面的代码才不会出错
    if (e.Item.ItemType == ListItemType.Header)
    {
      CheckBox CheckBox1 = e.Item.FindControl("CheckBox1") as CheckBox;
      CheckBox1.Checked = true;
    }

    //要改变内容,需要e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem
    //不加判断,是会出错的,
    //也可以使用if(e.Item.ItemIndex >-1)进行判断
    if (e.Item.ItemType == ListItemType.Item)
    {
      Label x = e.Item.FindControl("x") as Label;
      x.Text = "修改过的内容";
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
    RepeatLayout="Flow" OnItemDataBound="DataList1_ItemDataBound">
    <HeaderTemplate>
      <asp:CheckBox ID="CheckBox1" runat="server" />
    </HeaderTemplate>
    <ItemTemplate>
      <div style="background-color: Silver">
        <asp:Label ID="x" runat="server" Text="Label1"></asp:Label>
        <%#Container.DataItem%></div>
    </ItemTemplate>
    <AlternatingItemTemplate>
      <div style="background-color: Green">
        <asp:Label ID="x" runat="server" Text="Label1"></asp:Label>
        <%#Container.DataItem%></div>
    </AlternatingItemTemplate>
  </asp:DataList>
  </form>
</body>
</html>