您的位置:首页 > 数据库

Linq to sql(三):增删改(三)

2010-06-01 13:45 381 查看
前面创建Linq to sql Classes的时候我们输入名字GuestBook,系统就为我们自动创建了GuestBookDataContext

(你也可以在GuestBook.Designer.cs中找到类定义)。在绑定的时候我们使用查询句法查询留言表中所有留言,

按照发表时间倒序(天哪?这是数据访问吗?好像仅仅定义了一句SQL啊)。在发表留言按钮中,

我们为一个tbGuestBook赋值,然后把它加入留言表,再提交更改,就这样完成了记录的插入。

运行效果如下图:



然后,再创建一个Admin.aspx,前台代码如下:

<div>

<asp:Repeater ID="rpt_Message" runat="server" OnItemCommand="rpt_Message_ItemCommand">

<ItemTemplate>

<table width="600px" style="border:solid 1px #666666; font-size:10pt; background-color:#f0f0f0">

<tr>

<td align="left" width="400px">

<%# Eval("Message")%>

</td>

<td align="right" width="200px">

<%# Eval("PostTime")%> - <%# Eval("UserName")%>

</td>

</tr>

<tr>

<td colspan="2" align="right">

<hr width="300px" />

<asp:Button ID="btn_DeleteMessage" runat="server" Text="删除留言" CommandName="DeleteMessage" CommandArgument='<%# Eval("ID")%>'/>

管理员回复:<asp:TextBox runat="server" ID="tb_Reply" TextMode="MultiLine" Width="300px" Text='<%# Eval("Reply")%>'/>

<asp:Button ID="btn_SendReply" runat="server" Text="发表回复" CommandName="SendReply" CommandArgument='<%# Eval("ID")%>'/>

</td>

</tr>

</table>

<br/>

</ItemTemplate>

</asp:Repeater>

</div>

后台代码:

public partial class Admin : System.Web.UI.Page

{

GuestBookDataContext ctx = new GuestBookDataContext("server=xxx;database=GuestBook;uid=xxx;pwd=xxx");

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

SetBind();

}

}

private void SetBind()

{

rpt_Message.DataSource = from gb in ctx.tbGuestBooks orderby gb.PostTime descending select gb;

rpt_Message.DataBind();

}

protected void rpt_Message_ItemCommand(object source, RepeaterCommandEventArgs e)

{

if (e.CommandName == "DeleteMessage")

{

StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true);

ctx.Log = sw;

tbGuestBook gb = ctx.tbGuestBooks.Single(b => b.ID == new Guid(e.CommandArgument.ToString()));

ctx.tbGuestBooks.Remove(gb);

ctx.SubmitChanges();

SetBind();

sw.Close();

}

if (e.CommandName == "SendReply")

{

StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true);

ctx.Log = sw;

tbGuestBook gb = ctx.tbGuestBooks.Single(b => b.ID == new Guid(e.CommandArgument.ToString()));

gb.Reply = ((TextBox)e.Item.FindControl("tb_Reply")).Text;

gb.IsReplied = true;

ctx.SubmitChanges();

SetBind();

sw.Close();

}

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: