漫谈DataList的用法
<一> 数据库绑定:
con.Open();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("select * from person", con);
DataSet ds = new DataSet();
sda.Fill(ds, "person");
this.DataList1.DataKeyField = "pid";
this.DataList1.DataSource = ds.Tables["person"];
this.DataList1.DataBind();
<二> Datalist属性生成器
编辑 更新,删除,取消 的CommandName分别是edit update delete cancel ,这样在datalist的事件中就可以直接响应这些事件,以便进行操作。
样式有列表如下:
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" OnEditCommand="DataList1_EditCommand" OnCancelCommand="DataList1_CancelCommand" OnUpdateCommand="DataList1_UpdateCommand">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="select">查看详细信息</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="edit" OnClick="LinkButton2_Click">编辑</asp:LinkButton>
<asp:LinkButton ID="LinkButton5" runat="server" CommandName="delete">删除</asp:LinkButton><%# DataBinder.Eval(Container.DataItem ,"pname") %><%# DataBinder.Eval(Container.DataItem ,"psex") %>
</ItemTemplate>
<SelectedItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"pid","序列号:{0}") %><br>
<%# DataBinder.Eval(Container.DataItem,"pname") %>
<%# DataBinder.Eval(Container.DataItem,"psex") %>
</SelectedItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton3" runat="server" CommandName="cancel">取消</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" runat="server" CommandName="update">保存</asp:LinkButton>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem ,"pname") %>'></asp:TextBox>
</EditItemTemplate>
<AlternatingItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False"
Font-Strikeout="False" Font-Underline="False" ForeColor="Maroon" />
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False"
Font-Underline="False" ForeColor="Green" />
</asp:DataList>
程序代码:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "select")
{
this.DataList1.SelectedIndex = e.Item.ItemIndex;//选择
this.DataList1.DataBind();
}
}
protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
this.DataList1.EditItemIndex = e.Item.ItemIndex;//编辑
this.DataList1.DataBind();
}
{
this.DataList1.EditItemIndex = -1;//取消
this.DataList1.DataBind();
}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)//更新
{
string pid=this.DataList1.DataKeys[e.Item.ItemIndex].ToString();
string name = ((TextBox)e.Item.FindControl("TextBox1")).Text;
SqlConnection con = connecttion.ado.sqldb();
con.Open();
SqlCommand cmd = new SqlCommand("update person set pname='"+name+ "'where pid='" + pid + "'",con);
cmd.ExecuteNonQuery();
this.DataList1.EditItemIndex = -1;
this.DataList1.DataBind();
Response.Write(pid+name);
}
}