主要是练习Linq的插入,更新和删除操作.首先建一个Linq To Sql Class,并讲测试数据库的Post和Commnet两张表拖入,下面用代码说话








UID:
PID:
CONNTEXT:



UID:
PID:
CONNTEXT:


protected void Page_Load(object sender, EventArgs e)
{
bindGrid();
}
//为GridView绑定数据
void bindGrid()
{
LinqTestDC dc = new LinqTestDC();
this.grdPostInfo.DataSource = dc.Post;
this.grdPostInfo.DataBind();
}
//新增一条数据
protected void btnAdd_Click(object sender, EventArgs e)
{
LinqTestDC dc = new LinqTestDC();
Post PostInfo = new Post();
PostInfo.pid = Convert.ToInt32(txtPID.Text);
PostInfo.uid = Convert.ToInt32(txtUID.Text);
PostInfo.p_content = txtContent.Text;
dc.Post.Add(PostInfo);
dc.SubmitChanges();
bindGrid();
}
//GridView绑定事件
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes.Add("onclick","return rowclick(" + e.Row.DataItemIndex + ");");
}
//更新
protected void btnUpdate_Click(object sender, EventArgs e)
{
LinqTestDC dc = new LinqTestDC();
Post PostInfo = dc.Post.Single(p=>p.pid == Convert.ToInt32(txtPID2.Text));
PostInfo.p_content = txtContent2.Text;
dc.SubmitChanges();
bindGrid();
}
//删除一条数据(全删除用RemoveAll)
protected void btnDelete_Click(object sender, EventArgs e)
{
LinqTestDC dc = new LinqTestDC();
Post PostInfo = dc.Post.Single(p => p.pid == Convert.ToInt32(txtPID2.Text));//Lambda表达式p => p....
dc.Post.Remove(PostInfo);
dc.SubmitChanges();
bindGrid();
}

Back