using System.Data.SqlClient;

public partial class GridViewDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        SqlConnection cn = new SqlConnection(@"server=.\sqlexpress;uid=sa;pwd=;database=pubs");
        SqlCommand cmd = new SqlCommand("select * from authors", cn);
        cn.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataKeyNames = new string[] { "au_id"};
        GridView1.DataBind();
        cn.Close();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex= e.NewEditIndex;
        BindGrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        SqlConnection cn = new SqlConnection(@"server=.\sqlexpress;uid=sa;pwd=;database=pubs");
        SqlCommand cmd = new SqlCommand("update authors set au_lname=@au_lname, state=@state,contract=@contract where au_id=@au_id", cn);
        cmd.Parameters.Add("@au_id", SqlDbType.VarChar).Value = GridView1.DataKeys[e.RowIndex].Value.ToString();
        cmd.Parameters.Add("@au_lname", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
        cmd.Parameters.Add("@state", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
        cmd.Parameters.Add("@contract", SqlDbType.Bit).Value = ((CheckBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Checked;
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SqlConnection cn = new SqlConnection(@"server=.\sqlexpress;uid=sa;pwd=;database=pubs");
        SqlCommand cmd = new SqlCommand("delete from authors where au_id=@au_id", cn);
        cmd.Parameters.Add("@au_id",SqlDbType.VarChar).Value=GridView1.DataKeys[e.RowIndex].Value.ToString();
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }
}
posted on 2008-07-24 13:56  Liran  阅读(170)  评论(0编辑  收藏  举报