[ASP.NET][GridView] GridView 新刪修

  • 11673
  • 0

[ASP.NET][GridView] GridView 新刪修

Introduction

初學者(我),是需要好好弄懂這個控制項的,自己練習的一下基本新刪修功能,筆記一下。

是個示意範例,望各位客官別太計較。

 

Examples

資料庫:北風

版面配置:

2010-08-04_004219

 

 

.aspx

2010-08-04_004503

 

程式碼(.aspx.cs):

 //設定光棒效果
    private void SetLightStick(object sender, GridViewRowEventArgs e) {
        //判斷是否為資料行
        if (e.Row.RowType == DataControlRowType.DataRow) {
            int iIndex = e.Row.RowIndex;
            //當滑鼠停留時更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#11B5EA'");
            //當滑鼠移動後還原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        }
    }

    //GridView_OnRowDataBound
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
        this.SetLightStick(sender, e);
    }

    //新增儲存
    protected void lkbSaveF_Click(object sender, EventArgs e) {
        //...儲存至資料庫
    }

    //取消新增
    protected void lkbCancelF_Click(object sender, EventArgs e) {
        this.DoCancelAdd();
    }

    //編輯
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
        this.GridView1.EditIndex = e.NewEditIndex;
        this.GridView1.DataBind();
    }

    //更新
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
        //取得個欄位資料
        string sTerritoryDescription = ((TextBox)this.GridView1.Rows[e.RowIndex].FindControl("txbTDE")).Text.Trim();

        //...更新至資料庫
    }

    //執行取消編輯
    protected void DoCancelEidt() {
        this.GridView1.EditIndex = -1;
        this.GridView1.DataBind();
    }

    //執行取消新增
    protected void DoCancelAdd() {
        this.GridView1.ShowFooter = false;
        this.GridView1.DataBind();
    }

    //編輯
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
        this.DoCancelEidt();
    }


    //Add_OnClick
    protected void btnAdd_Click(object sender, EventArgs e) {
        this.DoAdd();
    }

    //新增資料
    private void DoAdd() {
        this.GridView1.ShowFooter = true;
        this.GridView1.DataBind();
    }

 

執行效果

1.檢視

2010-08-04_010231

2.修改

2010-08-04_005735 

 

3.新增

2010-08-04_010106

 

範例並未盡善,只是一個概念,當然網路上還是有許多精彩的範例。

 

程式碼下載:

三小俠  小弟獻醜,歡迎指教