转载 GridView和DetailView实现增,删,改,查收藏

新一篇: dataGrid捕获双击事件 | 旧一篇:  反射技术与设计模式

后台代码
public partial class GridViewExercise : System.Web.UI.Page
{
    
string ConStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

    
protected void Page_Load(object sender, EventArgs e)
    
{

        SortExprssion();
        SetGridView();
        
if (!IsPostBack)
        
{
            ViewState[
"CompanyName"= "SupplierID";
            ViewState[
"Direction"= "ASC";
            BindGridView();
        }

    }



    
//设置排序表达式
    private void SortExprssion()
    
{
        GridView1.Columns[
3].SortExpression = GridView1.Columns[3].HeaderText.ToString();
    }


    
//设置gridview的属性
    private void SetGridView()
    
{
        GridView1.AllowPaging 
= true;
        GridView1.AllowSorting 
= true;
    }


    
private void  BindGridView()
    
{
        
string QueryCon = "SELECT SupplierID,CompanyName,ContactName,Address,City FROM Suppliers";
        SqlConnection NorthWindCon 
= new SqlConnection(ConStr);
        SqlDataAdapter NorthWindDa 
= new SqlDataAdapter(QueryCon,ConStr);
        DataSet Ds 
= new DataSet();
        NorthWindDa.Fill(Ds, 
"Suppliers");
        GridView1.DataKeyNames 
= new string[] "SupplierID" };
        DataView Dv 
= Ds.Tables["Suppliers"].DefaultView;
        
//排序表达式
        string SortExpress = (string)ViewState["CompanyName"+ " " + (string)ViewState["Direction"];
        Dv.Sort 
= SortExpress;
        
//GridView1.DataSource = Ds.Tables["Suppliers"];
        
//绑定数据源
        GridView1.DataSource = Dv;
        GridView1.DataBind();
    }


    
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    
{

        
if (GridView1.EditIndex != -1)
        
{
            e.Cancel 
= true;
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('编辑模式下禁止换行')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
else
        
{
            DetailsView1.Visible 
= false;
            GridView1.EditIndex 
= e.NewEditIndex;
            BindGridView();
        }

    }



    
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    
{
        GridView1.EditIndex 
= -1;
        BindGridView();
    }



    
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    
{
        
string KeyId = GridView1.DataKeys[e.RowIndex].Value.ToString();
        
string CompanyName = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[1]).Text.ToString());
        
string ContactName = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[1]).Text.ToString());
        
string Address = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[1]).Text.ToString());
        
string City = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[1]).Text.ToString());

        
string UpdateStr = "UPDATE Suppliers SET CompanyName='" + CompanyName + "',ContactName='" + ContactName + "'," +
        
"Address='" + Address + "',City='" + City + " 'WHERE SupplierID='" +KeyId + "";
        SqlConnection UpdateCon 
= new SqlConnection(ConStr);
        SqlCommand UpdateCmd 
= new SqlCommand(UpdateStr,UpdateCon);
        
try
        
{
            UpdateCon.Open();
            UpdateCmd.ExecuteNonQuery();
            GridView1.EditIndex 
= -1;
            BindGridView();
        }

        
catch(Exception ex)
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('更新出错,请重新编辑')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
finally
        
{
            UpdateCon.Dispose();
        }

    }


    
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    
{
        
string KeyId = GridView1.DataKeys[e.RowIndex].Value.ToString();
        
string DeleteStr = "DELETE FROM Suppliers WHERE SupplierID='" + KeyId + "'";
        SqlConnection DeleteCon 
= new SqlConnection(ConStr);
        SqlCommand DeleteCmd 
= new SqlCommand(DeleteStr, DeleteCon);
        
try
        
{
            DeleteCon.Open();
            DeleteCmd.ExecuteNonQuery();
            BindGridView();
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('删除成功')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
catch (Exception ex)
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('删除出错,请检查数据是否有关联')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
finally
        
{
            DeleteCon.Dispose();
        }

    }


    
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.RowType == DataControlRowType.DataRow)
        
{
            
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            
{
                ((Button)e.Row.Cells[
2].Controls[0]).Attributes["onclick"= "if(!confirm('你真的要删除" + e.Row.Cells[3].Text + "这条记录么?'))return   false;";
            }

        }

    }



    
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    
{
        String SortExpress 
= e.SortExpression;
        
if (ViewState["CompanyName"].ToString() == SortExpress)
        
{
            
if (ViewState["Direction"].ToString() == "DESC")
            
{
                ViewState[
"Direction"= "ASC";
            }

            
else
            
{
                ViewState[
"Direction"= "DESC";
            }

        }

        
else
        
{
            ViewState[
"CompanyName"= e.SortExpression;
        }

        BindGridView();
    }


    
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    
{
        GridView1.PageIndex 
= e.NewPageIndex;
        BindGridView();
    }


    
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    
{
        
//if (GridView1.EditIndex != -1)
        
//{
        
//    GridView1.SelectedIndex = -1;
        
//    e.Cancel = true;
        
//    Literal TxtMsg = new Literal();
        
//    TxtMsg.Text = "<script>alert('编辑模式下禁止选择其他行')</script>";
        
//    Page.Controls.Add(TxtMsg);
        
//}
        
//else
        
//{
        
//    Literal TxtMsg = new Literal();
        
//    TxtMsg.Text = "您选择了第" + (e.NewSelectedIndex + 1) + "行,详细信息如下:<br />";
        
//        for(int i=3;i<GridView1.Columns.Count-1;i++)
        
//        {
        
//            TxtMsg.Text += GridView1.Columns[i].HeaderText + ":" + ((Label)GridView1.Rows[e.NewSelectedIndex].Cells[i].Controls[1]).Text + ",";
        
//        }
        
//    Page.Controls.Add(TxtMsg);
        
//}
        
//绑定detailview并显示
        if (e.NewSelectedIndex >= 0)
        
{
            Session[
"ID"= ((Label)GridView1.Rows[e.NewSelectedIndex].Cells[3].Controls[1]).Text.ToString();
            BindDetailView(Session[
"ID"].ToString());
            DetailsView1.Visible 
= true;

        }

    }


    
private void BindDetailView(string SelectId)
    
{
        
string QueryCon = "SELECT SupplierID,CompanyName,ContactName,Address,City FROM Suppliers WHERE SupplierID='" + SelectId + "";
        SqlConnection DetailCon 
= new SqlConnection(ConStr);
        SqlDataAdapter Da 
= new SqlDataAdapter(QueryCon, DetailCon);
        DataSet DetailDs 
= new DataSet();
        Da.Fill(DetailDs, 
"Suppliers");
        DetailsView1.DataSource 
= DetailDs.Tables["Suppliers"];
        DetailsView1.DataBind();
    }


    
//插入新的一行数据
    protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    
{
        ((TextBox)DetailsView1.Rows[
0].Cells[1].Controls[0]).ReadOnly = true;
        
//找到detailview中的行中控件的值
        string CompanyName = Server.HtmlEncode(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);
        
string ContactName = Server.HtmlEncode(((TextBox)DetailsView1.Rows[2].Cells[1].Controls[0]).Text);
        
string Address = Server.HtmlEncode(((TextBox)DetailsView1.Rows[3].Cells[1].Controls[0]).Text);
        
string City = Server.HtmlEncode(((TextBox)DetailsView1.Rows[4].Cells[1].Controls[0]).Text);

        
string InsertQuery = "INSERT INTO Suppliers (CompanyName,ContactName,Address,City) VALUES ('" + CompanyName + "','" + ContactName + "','" + Address + "','" + City + "')";
        SqlConnection InsertCon 
= new SqlConnection(ConStr);
        SqlCommand InsertCmd 
= new SqlCommand(InsertQuery,InsertCon);
        
try
        
{
            InsertCon.Open();
            InsertCmd.ExecuteNonQuery();
            BindGridView();
            BindDetailView(Session[
"ID"].ToString());
        }

        
catch (Exception Ex)
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('插入新数据出错,请重新输入')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
finally
        
{
            InsertCon.Dispose();
        }

        
    }


    
//改变detailsview的模式
    protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
    
{
        
//判断模式
        if (e.NewMode ==DetailsViewMode.Insert)
        
{
            DetailsView1.ChangeMode(DetailsViewMode.Insert);
        }

        
else if (e.NewMode == DetailsViewMode.Edit)
        
{
            DetailsView1.ChangeMode(DetailsViewMode.Edit);