加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

asp.net根据条件动态生成GridView,并动态绑定列,且可对其进行编辑的实现

(2012-01-13 08:20:47)
标签:

杂谈

分类: ASP.NET

前台代码:

<%@ Page Language="C#" CodeFile="List.aspx.cs" Inherits="manager_general_List" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body style="font-size: 12px;">
    <form id="form1" runat="server">
    <img src="../images/arrow03.gif" /><span style="font-weight: bold">
        <asp:Literal ID="ltl_listName" runat="server"></asp:Literal></span><br />
    <div style="clear: both; height: 20px; width: 100%;">
    </div>
    </form>
</body>
</html>

=======================================================================

后台代码:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Drawing;

public partial class manager_general_List : System.Web.UI.Page
{

    GridView gvshow = null;//定义全局变量
    public static bool sign;

    protected void Page_Load(object sender, EventArgs e)
    {
        string tbName = "";
        if (Request.QueryString["t"]!=null&&Request.QueryString["t"]!="")
        {
            tbName=Request.QueryString["t"].ToString();
        }
        else
        {
            common.MsgBox("没有相应的内容!");//此为自定的弹出消息框函数。使用者可自选定义。或者去掉。
            Response.End();
        }

        if (sign != null) //根据标记符号来判断,重新绑定那个控件
        {
            if (sign ==false)
            {

                string sql = getListSql(tbName);//获取要在gridview中显示的字段
                if (sql=="")
                {
                    common.MsgBox("没有相应的内容!");//此为自定的弹出消息框函数。使用者可自选定义。或者去掉。
                    Response.End();
                }
                try
                {
                    setBind(sql,tbName);
                    ltl_listName.Text = common.getFieldValueFromTab("tb_showname", "ctbname", tbName, 0, "cshowname")+"列表";
                }
                catch (System.Exception errr)
                {
                    common.MsgBox("没有相应的内容!");//此为自定的弹出消息框函数。使用者可自选定义。或者去掉。
                    Response.End();
                }
               
             }

        }

    }

    //获取要在gridview中显示的字段的sql
    public string getListSql(string tbName)
    {
        string sqlStr = "";
        string temp = "";
        DataSet ds = common.RunQuery("select * from tb_listfield where cname='" + tbName + "' order by cindex");
        if (ds.Tables.Count>0)
        {
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                temp += row["cfield"].ToString()+",";
            }
        }
        if (temp!="")
        {
            temp = temp.Substring(0, temp.Length - 1);//去掉最后一个逗号
            sqlStr = "select " + temp + " from " + tbName;
        }
        return sqlStr;
    }

    public void setBind(string sql,string tbName)
    {
       
        DataTable dt = getDataTable(sql); //获得数据源
        string headerText = "";

        gvshow = new GridView();//new一个grideview
        gvshow.Width = Unit.Pixel(700);//宽度
        gvshow.AlternatingRowStyle.BackColor =Color.FromArgb(0xF2,0xF2,0xF2);//偶数行的颜色
        gvshow.HeaderStyle.BackColor = Color.FromArgb(0xF2, 0xF2, 0xF2);//表头的颜色
        gvshow.HeaderStyle.Font.Bold = true;

        gvshow.AutoGenerateColumns = false;//设置自动产生列为false
        gvshow.RowEditing += new GridViewEditEventHandler(gvshow_RowEditing); //添加编辑事件
        gvshow.RowDeleting += new GridViewDeleteEventHandler(gvshow_RowDeleting);//添加删除事件
        gvshow.DataSource = dt;//设置数据源

        //遍历数据源所有的列,并绑定到gridview
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            BoundField bc = new BoundField();
            bc.DataField = dt.Columns[i].ColumnName.ToString();
           
            headerText = dt.Columns[i].Caption.ToString();

            //替换表头文字
            DataSet hDs=common.RunQuery("select top 1 * from tb_listfield where cname='"+tbName+"' and cfield='"+headerText+"'");
            if (hDs.Tables.Count>0)
            {
                if (hDs.Tables[0].Rows.Count>0)
                {
                    headerText = hDs.Tables[0].Rows[0]["cheadertext"].ToString();
                }
            }
            bc.HeaderText = headerText;

            bc.ItemStyle.HorizontalAlign =HorizontalAlign.Center;//居中对齐
            gvshow.Columns.Add(bc);
        }

        //添加编辑列
        CommandField cf = new CommandField();//命令字段
        cf.ButtonType = ButtonType.Link;//超链接样式的按钮
        cf.ShowEditButton = true;//显示编辑按钮
        cf.CausesValidation = false;//引发数据验证为false
        cf.HeaderText = "编辑";
        cf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        gvshow.Columns.Add(cf);//添加编辑按钮到gridview


        //添加删除列
        CommandField cf2 = new CommandField();
        cf2.ButtonType = ButtonType.Link;
        cf2.ShowDeleteButton = true;//显示删除按钮
        cf2.CausesValidation = false;
        cf2.HeaderText = "删除";
        cf2.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        gvshow.Columns.Add(cf2);

        //添加包复选框的模板列
        TemplateField tf = new TemplateField();
        tf.ItemTemplate = new MyTemplate("", DataControlRowType.DataRow);
        //tf.HeaderText = "选择";
        tf.HeaderTemplate = new MyTemplate("", DataControlRowType.Header);
        tf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        gvshow.Columns.Add(tf);


      

        gvshow.DataBind();

        form1.Controls.Add(gvshow);
    }
   
    //删除gridview的行
    void gvshow_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int i = e.RowIndex;
        Response.Write("delete:" + gvshow.Rows[i].Cells[0].Text.ToString());
    }


    //编辑行
    public void gvshow_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int i = e.NewEditIndex;
        string id = gvshow.Rows[i].Cells[0].Text.ToString();

        Response.Write("you want to edit" + id);
    }


    //获得数据表
    public DataTable getDataTable(string sql)
    {
        DataTable dt = common.RunQuery(sql).Tables[0];
        return dt;
    }

}

=======================================================================

创建模板列的类文件名:MyTemplate.cs

类代码:

using System;
using System.Collections.Generic;
using System.Web;


using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/////添加包复选框的模板列的类
/// </summary>
public class MyTemplate : ITemplate
{
    private string strColumnName;
    private DataControlRowType dcrtColumnType;

    public MyTemplate()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 动态添加模版列
    /// </summary>
    /// <param name="strColumnName">列名</param>
    /// <param name="dcrtColumnType">列的类型</param>
    public MyTemplate(string strColumnName, DataControlRowType dcrtColumnType)
    {
        this.strColumnName = strColumnName;
        this.dcrtColumnType = dcrtColumnType;
    }

    public void InstantiateIn(Control ctlContainer)
    {
        switch (dcrtColumnType)
        {
            case DataControlRowType.Header: //列标题

                //如果头部使用标题则使用以下代码
                //Literal ltr = new Literal();
                //ltr.Text = strColumnName;
                //ctlContainer.Controls.Add(ltr);
               
                //头部也创建一个checkbox,则使用如下代码
                CheckBox cbh = new CheckBox();
                cbh.ID = "CheckBox1";
                cbh.Checked = false;
                ctlContainer.Controls.Add(cbh);
                break;
            case DataControlRowType.DataRow: //模版列内容——加载CheckBox
                CheckBox cb = new CheckBox();
                cb.ID = "CheckBox1";
                cb.Checked = false;
                ctlContainer.Controls.Add(cb);
                break;
        }
    }

}

==================================================================

common.cs类代码

using System;
using System.Collections.Generic;

using System.Web;

using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Drawing;

using System.Security.Cryptography;//使用md5
using System.Text.RegularExpressions;//正则表达式命名空间

/// <summary>
///common 的摘要说明
/// </summary>
public class common
{

    public common()
{
   //
   //TODO: 在此处添加构造函数逻辑
   //
}


    //获取数据库链接
    public static OleDbConnection getConn()
    {
        string myPath=System.Web.HttpContext.Current.Server.MapPath( "~/ ");
        myPath+="App_Data\\xxxx.mdb";
        return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + myPath + ";Persist Security Info=True");
   
    }

    //运行查询
    public static DataSet RunQuery(String QueryString)
    {

        // 声明连接字符串。本示例使用oledb
        //连接到xxxx.mdb数据库

        OleDbConnection DBConnection = common.getConn();
        OleDbDataAdapter DBAdapter;
        DataSet ResultsDataSet = new DataSet();

        try
        {

            //运行查询并建立一个数据集
            DBAdapter = new OleDbDataAdapter(QueryString, DBConnection);
            DBAdapter.Fill(ResultsDataSet);

            //关闭数据库连接
            DBConnection.Close();

        }
        catch (Exception ex)
        {

            //如果数据库连接仍然打开则关闭它
            if (DBConnection.State == ConnectionState.Open)
            {
                DBConnection.Close();
            }
            MsgBox("无法连接到数据库!");
            System.Web.HttpContext.Current.Response.Write("<script>history.back(1);</script>");

        }

        return ResultsDataSet;

    }

    //弹出消息框
    public static void MsgBox(string msg)
    {
        System.Web.HttpContext.Current.Response.Write("<script>alert('" + msg + "')</script>");
    }

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有