protected void Page_Load(object sender, EventArgs e)
{
getdata();
}
//获取数据绑定在GV1上
private void getdata()
{
DataClassesDataContext db = new DataClassesDataContext(); //数据源
var query = from a in db.stu_mark select new { a.ID, a.mark,a.name,a.number,a.course,a.credit }; //创建查询,将两个表关联起来查询
GridView1.DataSource = query;//执行查询,将数据显示在GV1
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataClassesDataContext ctx = new DataClassesDataContext();
List<stu_mark> contents = new List<stu_mark>();
contents = ctx.stu_mark.ToList();
GridView1.DataSource = contents;
GridView1.DataBind();
stu_mark one = new stu_mark();
one.name = TextBox1.Text;
one.number = TextBox2.Text;
one.course = TextBox3.Text;
one.credit = TextBox4.Text;
one.mark = TextBox5.Text;
ctx.stu_mark.InsertOnSubmit(one);
ctx.SubmitChanges();
}
protected void GridView1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
{
string strID = GridView1.DataKeys[e.RowIndex].Value.ToString();
int intstrID = Convert.ToInt32(strID);
DataClassesDataContext ctx = new DataClassesDataContext();//数据源
var query = from a in ctx.stu_mark
where a.ID == intstrID
select a;
ctx.stu_mark.DeleteAllOnSubmit(query);//删除
ctx.SubmitChanges();//更新
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Login.aspx");
Response.End();
}
}
为什么删两次才能在表中删除,添加的时候也是,第一次添加的时候数据库中就已经加上了,但是表中不显示,第二次添加表里才显示
------解决方案--------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
getdata();
}
}
//获取数据绑定在GV1上
private void getdata()
{
DataClassesDataContext db = new DataClassesDataContext(); //数据源
var query = from a in db.stu_mark select new { a.ID, a.mark,a.name,a.number,a.course,a.credit }; //创建查询,将两个表关联起来查询
GridView1.DataSource = query;//执行查询,将数据显示在GV1
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataClassesDataContext ctx = new DataClassesDataContext();
List<stu_mark> contents = new List<stu_mark>();
contents = ctx.stu_mark.ToList();
GridView1.DataSource = contents;
GridView1.DataBind();
stu_mark one = new stu_mark();
one.name = TextBox1.Text;
one.number = TextBox2.Text;
one.course = TextBox3.Text;
one.credit = TextBox4.Text;
one.mark = TextBox5.Text;
ctx.stu_mark.InsertOnSubmit(one);
ctx.SubmitChanges();
getdata();
}
protected void GridView1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
{
string strID = GridView1.DataKeys[e.RowIndex].Value.ToString();
int intstrID = Convert.ToInt32(strID);
DataClassesDataContext ctx = new DataClassesDataContext();//数据源
var query = from a in ctx.stu_mark
where a.ID == intstrID
select a;
ctx.stu_mark.DeleteAllOnSubmit(query);//删除
ctx.SubmitChanges();//更新
getdata();
}
protected void Button2_Click(object sender, EventArgs e)