datalist的用法

时间:2021-01-01 22:16:20

DataList 提供相关的编辑模板,但和DataGrid不一样的是,DataList没有编辑按钮。要在DataList中使用编辑功能,可在项模板中增加一个按 钮,Linkbutton和Button都可以。在CommandName中设置为Edit就可以把此按钮和DataList的编辑事件联系起来了。
如:
编辑按钮可以使用CommandName="Edit"
更新按钮可以使用CommandName="Update"
取消按钮可以使用CommandName="Cancel"
删除按钮可以使用CommandName="Delete"
来实现。

-------------------------------------------------------------------------------------------------------------------------

控件设置:

<asp:DataList ID="UserList" DataKeyField="Uid" OnItemCreated="UserList_ItemCreated" OnUpdateCommand="UserList_OnUpdateCommand" OnDeleteCommand="UserList_OnDeleteCommand" runat="server" Width="100%" RepeatColumns="6" OnEditCommand="UserList_OnEditCommand" OnCancelCommand="UserList_OnCancelCommand">
    <HeaderTemplate>
     <table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#E2EEF5" >
    <tr>
      <td width="17%" height="25" align="center" bgcolor="#E8F0F7">登陆名称</td>
      <td width="15%" align="center" bgcolor="#E8F0F7">真实姓名</td>
      <td width="17%" align="center" bgcolor="#E8F0F7">所属用户组</td>
      <td width="25%" align="center" bgcolor="#E8F0F7">拥有权限</td>
      <td width="14%" align="center" bgcolor="#E8F0F7">创建时间</td>
      <td width="12%" align="center" bgcolor="#E8F0F7">操作</td>
    </tr>
    </HeaderTemplate>
    <ItemTemplate>
     <tr>
      <td height="25" bgcolor="#FFFFFF"><img src="data:images/FriendICO.gif" width="15" height="15" style="margin-left:5px;" />&nbsp;[<%#Eval("Uname")%>]<asp:Image ID="StateICO" ImageUrl='<%#GetUserState(Eval("uState").ToString()) %>' width="12" height="12" runat="server" /></td>
      <td align="center" bgcolor="#FFFFFF"><%#Eval("Rname")%></td>
      <td align="center" bgcolor="#FFFFFF"><%#Eval("UserGroup")%></td>
      <td align="center" bgcolor="#FFFFFF"><%#Eval("Purview")%></td>
      <td align="center" bgcolor="#FFFFFF"><%#Eval("Ctimes","{0:d}")%></td>
      <td align="center" bgcolor="#FFFFFF"><img src="data:images/Edit_ICOS.gif" width="14" height="15" border="0" align="absmiddle" /><asp:LinkButton CommandName="Edit"
              ID="Edit_But" ForeColor="#003366" runat="server">编辑</asp:LinkButton>&nbsp;<img src="data:images/DEL_ICOS.gif" width="14" height="15" border="0" align="absmiddle" /><asp:LinkButton CommandName="Delete"
              ID="Del_But" ForeColor="#003366" runat="server" >删除</asp:LinkButton></td>
    </tr>
    </ItemTemplate>
    <EditItemTemplate>
    <tr>
      <td height="25" bgcolor="#E8F0F7"><img src="data:images/FriendICO.gif" width="15" height="15" style="margin-left:5px;" />&nbsp;<%#Eval("Uname")%><asp:CheckBox ID="User_State" Checked='<%#GetBoxState(Eval("uState").ToString().Trim()) %>' runat="server" Text="启用账户" />
      </td>
          <td align="center" bgcolor="#E8F0F7"><asp:TextBox ID="User_Rname" runat="server" CssClass="inputX"
                  Text='<%#Eval("Rname")%>' Width="80px"></asp:TextBox>
          </td>
          <td align="center" bgcolor="#E8F0F7">
              <asp:DropDownList ID="User_Group" runat="server" CssClass="FontBlue12">
                  <asp:ListItem Value="Guest">来宾组</asp:ListItem>
                  <asp:ListItem Value="Editor">编辑组</asp:ListItem>
                  <asp:ListItem Value="System">系统组</asp:ListItem>
              </asp:DropDownList>
          </td>
          <td align="center" bgcolor="#E8F0F7">
              <asp:CheckBoxList ID="User_Priv" runat="server" CssClass="FontBlue12"
                  RepeatDirection="Horizontal">
                  <asp:ListItem Value="r">读</asp:ListItem>
                  <asp:ListItem Value="w">写</asp:ListItem>
                  <asp:ListItem Value="e">编辑</asp:ListItem>
                  <asp:ListItem Value="d">删除</asp:ListItem>
              </asp:CheckBoxList>
          </td>
           <td align="center" bgcolor="#E8F0F7"><%#Eval("Ctimes","{0:d}")%></td>
          <td align="center" bgcolor="#E8F0F7">
              <img align="absmiddle" border="0" height="15" src="data:images/Update_ICOS.gif"
                  width="14" /><asp:LinkButton ID="Update_But" runat="server"
                  CommandName="Update" ForeColor="#003366">更新</asp:LinkButton>&nbsp;<img align="absmiddle" border="0" height="15" src="data:images/Cancel_ICOS.gif"
                  width="14" /><asp:LinkButton ID="Cancel_But" runat="server"
                  CommandName="Cancel" ForeColor="#003366">取消</asp:LinkButton>
          </td>
      
    </tr>
    </EditItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
    </asp:DataList>

后台代码:

//取消编辑

protected void UserList_OnCancelCommand(object sender, DataListCommandEventArgs e)
    {
        this.UserList.EditItemIndex = -1;
        GetUserList();
    }

//DataList编辑

protected void UserList_OnEditCommand(object sender, DataListCommandEventArgs e)
    {
        this.UserList.EditItemIndex = e.Item.ItemIndex;
        GetUserList();
    }

//DataList更新

protected void UserList_OnUpdateCommand(object sender, DataListCommandEventArgs e)
    {
        string id = this.UserList.DataKeys[e.Item.ItemIndex].ToString(); //使用前需先设置DataList的DataKeyField="Uid"       
        string Rname = ((TextBox)e.Item.FindControl("User_Rname")).Text.Trim();//取得DataList中ID为"User_Rname"的TextBox中的值
        string UserGroup = ((DropDownList)e.Item.FindControl("User_Group")).SelectedValue.Trim();
        string UserPurview = "";
        for (int i = 0; i < ((CheckBoxList)e.Item.FindControl("User_Priv")).Items.Count; i++)
        {
            if (((CheckBoxList)e.Item.FindControl("User_Priv")).Items[i].Selected == true)
            {
                UserPurview += ((CheckBoxList)e.Item.FindControl("User_Priv")).Items[i].Value + ",";
            }
       
        }
        if (UserPurview != "")
        {
            UserPurview = UserPurview.Substring(0, UserPurview.Length - 1);
        }
        int usstate = 0;
        if (((CheckBox)e.Item.FindControl("User_State")).Checked == true)
        {
            usstate = 1;
        }
        string sql = "update SystemUser set uState =" + usstate + ",UserGroup='" + UserGroup + "',Rname='" + Rname + "',Purview='" + UserPurview + "' where uid=" + id + "";
        ConnDB db = new ConnDB();
        if (db.EditDatabase(sql))
        {
            msgBox.Alert("编辑成功!", "SysUser_Admin.aspx");
        }
        else
        {
            msgBox.Alert("编辑失败!" + ((CheckBox)e.Item.FindControl("User_State")).ToString());
        }

}

//DataList删除对话框

protected void UserList_ItemCreated(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            LinkButton lbDelete = (LinkButton)e.Item.FindControl("Del_But"); lbDelete.Attributes.Add("onclick", "return confirm(""确定删除这个用户吗?"");");
        }
    }

//DataList删除

protected void UserList_OnDeleteCommand(object sender, DataListCommandEventArgs e)
    {
        string id = this.UserList.DataKeys[e.Item.ItemIndex].ToString(); //使用前需先设置DataList的DataKeyField="Uid"
        string sql = "delete from SystemUser where Uid=" + id + "";
        ConnDB db = new ConnDB();
        if (db.EditDatabase(sql))
        {
            msgBox.Alert("已删除!", "SysUser_Admin.aspx");
        }
        else
        {
            msgBox.Alert("删除失败!", "SysUser_Admin.aspx");
        }
        GetUserList();
    }

//DataList数据绑定

private void DataListDataBind()
   {
    SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DataBaseCon"].ToString());
    SqlDataAdapter da=new SqlDataAdapter("select * from Employees",conn);
    DataSet ds=new DataSet();
    try
    {
     da.Fill(ds,"testTable");
     dlEditItem.DataSource=ds.Tables["testTable"];
     dlEditItem.DataBind();
    }
    catch(Exception error)
    {
     Response.Write(error.ToString());
    }
   }