Datalist增删改查——联系人管理

      关于Datalist,其实和Repeater差不多,都是存放数据的控件,相比较下,Datalist和Repeater虽然都是用的模板,但是Datalist比之多了Edit模板,也就是编辑栏的模板,事件中也多了Edit,Update,Cancel以及Delete,可以说更加智能,更全面了,但是也有很多的不方便,不够灵活,复杂程度高。

   下面就用联系人管理来详细说一下 Datalist的用法:

   

联系人管理要求:实现对联系人的增删改查。

    ① 当点击编辑时,编辑模板会覆盖原来的模板,而不会跳转页面。点击更新后,原来的模板重新覆盖掉编辑模板。点击取消,打回到原来的模板。总之就是不会跳转页面。  

    ②当点击"添加新人员"时,会在当前页面出现增加人员编辑栏原"添加新人员"按钮隐藏掉,当输入好人物信息后,点击添加。  增加人物编辑栏消失掉,原"添加新人员"按钮出现,并且"添加新人员"按钮要随着联系人列表高度的增长而相对下移。注意要在增加人物编辑栏加上非空验证,非空验证请注意分组!!!
    ③当点击删除时,弹出对话框"是否确认删除?"

   

  

   下面是代码:  在这里数据库有两个表,其中一个表是联系人列表,一个表是分组列表。主外键关系。

分组隐藏的是分组编号,显示的是分组名称。  为了获取点击编辑后 下拉列表首先选中的值,这里加了一个隐藏域用来存储分组的ID

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
        DataList1.DataSource = new ContactsBF().Select();
        DataList1.DataBind();
        DropDownList2.DataSource = new ContactsBF().SelectGroup(); //下拉列表要显示的值
        DropDownList2.DataTextField = "Name";
        DropDownList2.DataValueField = "id";
        DropDownList2.DataBind();
        }
    }
   
    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) //在数据被绑定时激发 (实现多表联合查询,通过编号显示名字)
    {     
        if (e.Item.ItemType == ListItemType.EditItem)  //判断一下是不是编辑项的模板
        {
            if (e.Item.ItemIndex > -1)  //从身体开始,不从表头开始,因为表头的索引为-1
            {
                //找到隐藏域的值
                HtmlInputHidden lt = (HtmlInputHidden)e.Item.FindControl("Hidden1");
                //找到下拉列表
                DropDownList dp = (DropDownList)e.Item.FindControl("DropDownList1");
                //为下拉列表赋值
                List<Groups> list = new ContactsBF().SelectGroup();
                dp.DataSource = list;
                dp.DataTextField = "Name";
                dp.DataValueField = "id";
                dp.SelectedValue = lt.Value;
                dp.DataBind();
            }
        }
        else 
        {
            if (e.Item.ItemIndex > -1)
            {
                Literal lt = (Literal)e.Item.FindControl("Literal1"); //找到这个控件
                //写方法查询名字       
                string GroupName = new ContactsBF().ToName(Convert.ToInt32(lt.Text));// 显示名字
                lt.Text = GroupName; //重新赋值
                LinkButton a = (LinkButton)e.Item.FindControl("LinkButton2");
                a.Attributes.Add("onclick", "return confirm("是否确认删除?")");
               
            }
        }
    }
    protected void DataList1_EditCommand(object source, DataListCommandEventArgs e) //当点击编辑按钮的时候,Item模版替换为Edit模板
    {   
        DataList1.EditItemIndex= e.Item.ItemIndex; //获取每列的索引,替换为Edit模板
//重新绑定
DataList1.DataSource = new ContactsBF().Select(); DataList1.DataBind(); } protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e) //点击更新按钮时触发 { if (e.Item.ItemIndex > -1) { //找到隐藏域的值,隐藏的值是主键,要通过主键修改 HtmlInputHidden lt = (HtmlInputHidden)e.Item.FindControl("Hidden2"); //首先先获取到文本框以及下拉列表的值 TextBox txt1 = (TextBox)e.Item.FindControl("TextBox1"); TextBox txt2 = (TextBox)e.Item.FindControl("TextBox2"); DropDownList dp = (DropDownList)e.Item.FindControl("DropDownList1"); new ContactsBF().Update(Convert.ToInt32(lt.Value), txt1.Text, txt2.Text, (dp.SelectedIndex+1)); //修改完毕,要打回到原来的页面 Response.Redirect("Default.aspx"); } } protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)//取消 { //直接打回到原来的界面 Response.Redirect("Default.aspx"); } protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e) //删除 { if(e.Item.ItemIndex>-1) { HtmlInputHidden lt = (HtmlInputHidden)e.Item.FindControl("Hidden3"); new ContactsBF().Delete(Convert.ToInt32(lt.Value)); Response.Redirect("Default.aspx"); } } protected void Button2_Click(object sender, EventArgs e) //当点击添加的时候 { string name = TextBox3.Text; string tel = TextBox4.Text; int groupid = DropDownList2.SelectedIndex; new ContactsBF().Insert(name,tel,groupid+1); Response.Redirect("Default.aspx"); }
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
    <style>
        .aa
         {
            position:relative;
            top:10px;
            left:245px;
            420px;
            height:100px;       
       
        }
        .bb 
        {
            position:relative;
            top:10px;
            left:245px;
            420px;
            height:0px;       
           
        }
        </style>
<body>
    <form id="form1" runat="server">
    <div >
    <center><h1>联系人管理</h1>
        <%--一旦生成DataList 就是生成了一个N行1列的表格--%>
        <asp:DataList ID="DataList1" runat="server"  OnItemDataBound="DataList1_ItemDataBound" OnEditCommand="DataList1_EditCommand" OnUpdateCommand="DataList1_UpdateCommand" OnCancelCommand="DataList1_CancelCommand" OnDeleteCommand="DataList1_DeleteCommand">   
            <HeaderTemplate>
                <table width="860px" border="0" cellpadding="1" cellspacing="2"> 
                    <tr>
                        <td width="200px">姓名</td>
                        <td width="200px">电话</td>
                        <td width="300px">分组</td>
                        <td>操作</td>
                    </tr>
                </table>
            </HeaderTemplate>
            <ItemTemplate>
                <table width="860px" >
                     <tr>
                        <td width="200px"><input id="Hidden3" type="hidden" runat="server" value='<%#Eval("id") %>'/><%#Eval("Name") %></td>
                        <td width="200px"><%#Eval("Tel") %></td>
                        <td width="300px"><asp:Literal ID="Literal1" runat="server" Text='<%#Eval("GroupId") %>'></asp:Literal></td>
                         <td><asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit">编辑</asp:LinkButton>&nbsp;&nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete"  >删除</asp:LinkButton></td>
                    </tr>
                </table>
            </ItemTemplate>
            <FooterTemplate></FooterTemplate>

          <%-- 编辑栏!!!--%>
            <EditItemTemplate>
                  <table width="860px" >
                     <tr>
                        <td width="200px"><br/><input id="Hidden2" type="hidden" runat="server" value='<%#Eval("id") %>'/><asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="名字不能为空" ControlToValidate="TextBox1"></asp:RequiredFieldValidator></td>
                        <td width="200px"><asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("Tel") %>'></asp:TextBox></td>
                        <td width="300px"><input id="Hidden1" type="hidden" runat="server" value='<%#Eval("GroupId") %>'/><asp:DropDownList ID="DropDownList1" runat="server"  ></asp:DropDownList></td>
                         <td><asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">更新</asp:LinkButton>&nbsp;&nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">取消</asp:LinkButton></td>
                    </tr>
                </table>
            </EditItemTemplate>  <%--编辑项模板--%>
        </asp:DataList></center>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <div class="bb" id="div2">
            <input id="Button1" type="button" value="添加新人员"  onclick="xianshi()"  />
        </div>
    </div>
        <div class="aa" id="div1" style="visibility:hidden" >
            姓名:<asp:TextBox ID="TextBox3" runat="server" ValidationGroup="aa"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="姓名不能为空" ControlToValidate="TextBox3" ValidationGroup="aa"></asp:RequiredFieldValidator><br/>
            电话:<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br />
            分组:<asp:DropDownList ID="DropDownList2" runat="server" ></asp:DropDownList><br/>
            <asp:Button ID="Button2" runat="server" Text="添加" OnClick="Button2_Click" ValidationGroup="aa"   />
        </div>
    </form>
</body>
</html>
<script src="Script/jquery-1.11.2.min.js"></script>
<script>
        function xianshi()
        {
            var a = document.getElementById("div1");  //获取到这个对象       
            //下面给这个对象移除属性   
            a.removeAttribute("style");
            var b = document.getElementById("div2");
            //下面给这个对象添加属性
            b.setAttribute("style", "visibility:hidden");
        }
    </script>

    

原文地址:https://www.cnblogs.com/lk-kk/p/4692153.html