GridViewの単純補助クラスをListでバインドする

4346 ワード

前提を用いてgridviewの汎用的な拡張方法を知り,反射の知識を知る.
using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Collections;

using System.ComponentModel;

using System.Collections.Generic;

using System.Reflection;



/// <summary>

///MyGridView      

/// </summary>

public class MyGridView

{

    GridView gv;

    IList list;

    Type t;

    object obj;

    public MyGridView( GridView gv,IList list,object obj)

    {

        this.gv = gv;

        this.list = list;

        this.obj = obj;

        if (list.Count > 0)

        {

            t = list[0].GetType();

        }

    }





    #region BindEvents



    public void BindEvents()

    {

        gv.RowEditing += new GridViewEditEventHandler(gv_RowEditing);

        gv.RowCancelingEdit += new GridViewCancelEditEventHandler(gv_RowCancelingEdit);

        gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);

        gv.RowUpdating += new GridViewUpdateEventHandler(gv_RowUpdating);

    }



    void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        int i = 0;

        PropertyInfo[] proInfo = t.GetProperties();

        foreach (TableCell cell in gv.Rows[e.RowIndex].Cells)

        {

            TextBox txtBox = cell.Controls[0] as TextBox;

            if (txtBox != null)

            {

                proInfo[i].SetValue(list[e.RowIndex], txtBox.Text, null);

            }

            

            i++;

        }

        obj.GetType().GetMethod("Save").Invoke(obj, null);

        

        gv.EditIndex = -1;

    }



    void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        list.RemoveAt(e.RowIndex);

    }



    void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        gv.EditIndex = -1;

    }



    void gv_RowEditing(object sender, GridViewEditEventArgs e)

    {

        gv.EditIndex = e.NewEditIndex;

    }

    #endregion



    public void BindData()

    {

        gv.DataSource = list;

        gv.DataBind();

    }

}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }