1.为GridView绑定数据源
/// <summary>
/// 绑定供求信息到GridViev控件
/// </summary>
/// <param name="type">供求信息类别</param>
private void GridViewBind(string type)
{
GridView1.DataSource = operation.SelectInfo(type);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.DataBind();
//显示当前页数
lblPageSum.Text = "当前页为 " + (GridView1.PageIndex + 1) + " / " + GridView1.PageCount + " 页";
}
2.设置初始绑定
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//高亮显示指定行
e.Row.Attributes.Add("onMouseOver", "Color=this.style.backgroundColor;this.style.backgroundColor='#FFF000'");
e.Row.Attributes.Add("onMouseOut", "this.style.backgroundColor=Color;");
//设置审核状态,并且设置相应的颜色。
if (e.Row.Cells[5].Text == "False")
{
e.Row.Cells[5].Text = StringFormat.HighLight("未审核", true);
}
else
{
e.Row.Cells[5].Text = StringFormat.HighLight("已审核", false);
}
//多余字 使用...显示
e.Row.Cells[2].Text = StringFormat.Out(e.Row.Cells[2].Text, 18);
//删除指定行数据时,弹出询问对话框
((LinkButton)(e.Row.Cells[7].Controls[0])).Attributes.Add("onclick", "return confirm('是否删除当前行数据!')");
}
}
3.选定按钮
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string id = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
Response.Write("<script> window.open('DetailInfo.aspx?id=" + id + "&&type=" + infoType + "','','height=258,width=679,top=200,left=200') </script>");
Response.Write("<script>history.go(-1)</script>");
}
4.删除按钮
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
operation.DeleteInfo(GridView1.DataKeys[e.RowIndex].Value.ToString());
GridviewBind(infoType); }
5.编辑、取消、更新
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridviewBind(infoType); //进入编辑状态后必须重新获取数据
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridviewBind(infoType); }
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex][0].ToString();
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString();//获取修改以后的值
string age = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();
string myclass = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();
SqlConnection conncetion = new SqlConnection("Data Source=GUWENPC;Initial Catalog=student;Persist Security Info=True;User ID=sa;Password=123456");
conncetion.Open();
SqlCommand cmd = new SqlCommand("update [class] set name='" + name + "',age='" + age + "',class='" + myclass + "' where id='" + id + "'", conncetion);
//sql语句书写时,注意变量与常量的区别
int num = cmd.ExecuteNonQuery();
conncetion.Close();
GridView1.EditIndex = -1; //回复为未编辑状态
GridviewBind(infoType);}
5.分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridViewBind(infoType);
}