一、页面代码:<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="post_id"
onpageindexchanging="GridView1_PageIndexChanging"
onrowdeleting="GridView1_RowDeleting"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="post_id" HeaderText="帖子编号" />
<asp:CommandField SelectText="查看详情" ShowSelectButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</div>
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
</asp:DetailsView>
</form>
</body>
</html>
二、后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace yangshuaiNew
{
public partial class WebForm3 : System.Web.UI.Page
{
string constr = "server=(local);database=Curriculum_knowledge_communication;trusted_connection=true";
public void bind()
{
string sqlstr = "select post_id from cPost";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlDataAdapter myadpt = new SqlDataAdapter(sqlstr, con);
DataSet myds = new DataSet();
myadpt.Fill(myds, "cPost");
GridView1.DataSource = myds;
GridView1.DataBind();
GridView1.DataKeyNames = new string[] { "post_id" };
con.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //页面首次加载时调用bind()函数
{
bind();
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//删除
string sqlstr = "delete from cPost where post_id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(sqlstr, con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
bind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//分页操作中页码变化时重新设置当前页的索引,并绑定数据显示
GridView1.PageIndex = e.NewPageIndex;
bind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
string sqlstr = "select * from cPost where post_id='" + GridView1.SelectedValue + "'";
SqlCommand cmd = new SqlCommand(sqlstr, con);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds, "cPost");
DetailsView1.DataSource = ds.Tables[0].DefaultView;
DetailsView1.DataBind();
}
}
}
三、出现的问题(GridView显示的不在了但DetailsView的数据还在)
四、解决方法
在删除代码里面添加
DetailsView1.DataSource = null;
DetailsView1.DataBind();