xml 학습(5) xml 구성 그리드뷰 열

黄舟
풀어 주다: 2017-02-23 14:36:04
원래의
1688명이 탐색했습니다.

 有时候我们不确定我们gridview要显示那些列,或者我们希望可以动态配置gridview那些列显示,以及宽度,这时可以通过可以把列的消息存放的数据库,通过读取数据库实现动态绑定列,也可以通过配置xml实现,当然也可以第一次通过读取xml,然后向数据库插入列消息,然后下一次判断数据库是否已经存储了列数据,如果没有存入,那么读取xml。

下面我讲解如何通过xml如何动态绑定gridview

一效果:

二,核心代码:

  1.读取xml文件,返回datatable

    /// <summary>
        /// 获取xmltable
        /// </summary>
        /// <param name="xmlname">xml名字</param>
        /// <returns></returns>
        public DataTable getDTXML(string xmlname)
        {
            DataTable result = new DataTable();
            string fileName = HttpContext.Current.Request.PhysicalApplicationPath + "\\Xml\\" + xmlname + ".xml";//xml的物理路径
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNodeList xWitsTablesList = xmlDoc.SelectNodes("/config");
            foreach (XmlNode xOracleNode in xWitsTablesList)
            {
                foreach (XmlNode node2 in xOracleNode.ChildNodes)
                {
                    if (node2.Name == "Header")
                    {
                        //   //绑定表头
                        foreach (XmlNode node3 in node2.Attributes)
                        {
                            result.Columns.Add(node3.Value);
                        }
                    }
                    else
                    {
                        //数据行
                        int i = 0;//列标志
                        DataRow dr = result.NewRow();
                        foreach (XmlNode node4 in node2.Attributes)
                        {
                            dr[i] = node4.Value.ToString();
                            i++;
                        }
                        result.Rows.Add(dr);
                    }

                }
            }
            return result;
        }
로그인 후 복사


2.绑定gridview列

    /// <summary>
    /// 绑定gridview列
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="dt"></param>
    /// <param name="width"></param>
    /// <param name="columnNumber"></param>
    public void HtmlGridView(GridView gv,DataTable dt,int width,int columnNumber)
    {
        try
        {
            int k=0;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    BoundField bf = new BoundField();
                    bf.HeaderText = dr["name"].ToString();
                    bf.DataField = dr["field_code"].ToString();
                    bf.HeaderStyle.Width = Convert.ToInt32(dr["width"].ToString());
                    bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                    bf.HeaderStyle.ForeColor = System.Drawing.Color.Black;
                    bf.SortExpression = dr["name"].ToString();
                    gv.Columns.Add(bf);
                    k+= Convert.ToInt32(dr["width"].ToString());
                    if (dr["width"].ToString()=="0")
                    {
                        gv.Columns[columnNumber].Visible = false;
                    }
                    columnNumber++;
                }
                gv.Width = k + width;
            }
 
        }
        catch(Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
로그인 후 복사


三,下面是全部源码:

HtmlGridView.aspx源码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HtmlGridView.aspx.cs" Inherits="HtmlGridView" %>

<!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 id="Head1" runat="server">
    <title>读取xml</title>
    <link rel="Stylesheet" type="text/css" href="Css/xmlReadOne.css" />
    <link rel="Stylesheet" type="text/css" href="Css/Common/InputStyle.css" />
    <script type="text/javascript"  src="Scripts/jquery-1.4.1.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <p>
    <p class="main">
      <p class="list">
        <asp:GridView runat="server" ID="gv_class" AutoGenerateColumns="False"  
              DataKeyNames="ID" Width="100%" CellPadding="4"  
              ForeColor="#333333" GridLines="None"   >
            <AlternatingRowStyle BackColor="White" />
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFFBD6"  HorizontalAlign="Center" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <SortedAscendingCellStyle BackColor="#FDF5AC" />
            <SortedAscendingHeaderStyle BackColor="#4D0000" />
            <SortedDescendingCellStyle BackColor="#FCF6C0" />
            <SortedDescendingHeaderStyle BackColor="#820000" />
            <Columns>
              <asp:TemplateField   HeaderText="NO">
                <ItemTemplate>
                  <%#Eval("NO") %>
                </ItemTemplate>
              </asp:TemplateField>
            </Columns>
        </asp:GridView>
      </p>
     </p>
    </p>
    </form>
</body>
 <script type="text/javascript">
     function add_clear() {
         $(".button").find("input[type=text] ").each(function () {
             $(this).val(&#39;&#39;);
         });
     }
    </script>
</html>
로그인 후 복사


HtmlGridView.aspx.cs源码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Web.UI.HtmlControls;
using IsXMLUtility;
using System.Data;

public partial class HtmlGridView : System.Web.UI.Page
{
    XmlHelper xmlHelper = new XmlHelper();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //gv_class绑定列
            DataTable dt = xmlHelper.getDTXML("表头");
            Functions.getInstance().HtmlGridView(gv_class, dt, 10, 1);

            InitGV();
        }
    }


    /// <summary>
    /// 绑定gridview
    /// </summary>
    private void InitGV()
    {
        DataTable dt = xmlHelper.getDTXML("内容", "NO", 1);
        this.gv_class.DataSource = dt.DefaultView;
        this.gv_class.DataBind();
    }

}
로그인 후 복사


表头.xml

<?xml version="1.0" encoding="utf-8" ?>
<config>
    <Header  col1="name"      col2="field_code" col3="width" col4="dispaly"  ></Header>
    <row     col1="班级编号"  col2="ID"         col3="100"   col4="true"     ></row>
    <row     col1="班级"      col2="class"      col3="100"   col4="true"     ></row>
    <row     col1="班级名称"  col2="class_name" col3="100"   col4="true"     ></row>
    <row     col1="年级"      col2="year"       col3="100"   col4="true"     ></row>
    <row     col1="学校"      col2="school"     col3="100"   col4="true"     ></row>
    <row     col1="人数"      col2="count"     col3="100"    col4="true"     ></row>
</config>
로그인 후 복사



内容.xml

<?xml version="1.0" encoding="utf-8" ?>
<config>
  <Header  col1="ID" col2="class" col3="class_name" col4="year" col5="school"  col6="count" ></Header>
  <row col1="一五班" col2="01" col3="实验班" col4="2013" col5="三峡高级中学"  col6="20" ></row>
  <row col1="一六班" col2="02" col3="奥数班" col4="2013" col5="三峡高级中学"  col6="25" ></row>
  <row col1="一六班" col2="03" col3="阳光班" col4="2013" col5="三峡高级中学"  col6="69" ></row>
</config>
로그인 후 복사


xmlReadOne.css

body{
margin:0 auto;
padding:0px;
font-family:&#39;宋体&#39;;
}
.main
{
     margin-left:20px;
     margin-top:10px;
     text-align:left;
    }
    
.button
{
    width:600px;
    border:#A8B7CC solid 1px;
	background-color:#FFFFFF;
    }
.content
{
    width:600px;
    border:#A8B7CC solid 1px;
	background-color:#E0EDFE;
    margin-top:20px;
 }
 .list
{
    width:600px;
    height:300px;
    overflow:auto;
    border:#A8B7CC solid 1px;
	background-color:#FFFFFF;
	overflow: scroll;
	SCROLLBAR-FACE-COLOR:#E0EDFE;
	PADDING-BOTTOM: 0px;
	SCROLLBAR-HIGHLIGHT-COLOR: #ffffff;
	SCROLLBAR-SHADOW-COLOR: #cccccc;
	SCROLLBAR-3DLIGHT-COLOR:#ffffff;
	SCROLLBAR-ARROW-COLOR:#95AFD4;
	PADDING-TOP: 0px;
	SCROLLBAR-TRACK-COLOR: #ffffff;
	SCROLLBAR-DARKSHADOW-COLOR: #ffffff;
	LETTER-SPACING: 1pt;
    margin-top:20px;
 }  
.gv
{
	width:600px;
	height:400px;
	margin-top:20px;
	border:#A8B7CC solid 1px;
	background-color:#FFFFFF;
	overflow: scroll;
	SCROLLBAR-FACE-COLOR:#E0EDFE;
	PADDING-BOTTOM: 0px;
	SCROLLBAR-HIGHLIGHT-COLOR: #ffffff;
	SCROLLBAR-SHADOW-COLOR: #cccccc;
	SCROLLBAR-3DLIGHT-COLOR:#ffffff;
	SCROLLBAR-ARROW-COLOR:#95AFD4;
	PADDING-TOP: 0px;
	SCROLLBAR-TRACK-COLOR: #ffffff;
	SCROLLBAR-DARKSHADOW-COLOR: #ffffff;
	LETTER-SPACING: 1pt;
}
로그인 후 복사


Functions.cs

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

/// 
///Server 的摘要说明
/// 
public class Functions
{
    private static object _synRoot=new object();
    private static Functions _instance=null;

    private Functions()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}
    public static Functions getInstance()
    {
        lock (_synRoot)
        {
            if (_instance == null)
            {
                _instance = new Functions();
            }
        }
        return _instance;
    }

    #region 业务层
    /// <summary>
    /// 绑定gridview列
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="dt"></param>
    /// <param name="width"></param>
    /// <param name="columnNumber"></param>
    public void HtmlGridView(GridView gv,DataTable dt,int width,int columnNumber)
    {
        try
        {
            int k=0;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    BoundField bf = new BoundField();
                    bf.HeaderText = dr["name"].ToString();
                    bf.DataField = dr["field_code"].ToString();
                    bf.HeaderStyle.Width = Convert.ToInt32(dr["width"].ToString());
                    bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                    bf.HeaderStyle.ForeColor = System.Drawing.Color.Black;
                    bf.SortExpression = dr["name"].ToString();
                    gv.Columns.Add(bf);
                    k+= Convert.ToInt32(dr["width"].ToString());
                    if (dr["width"].ToString()=="0")
                    {
                        gv.Columns[columnNumber].Visible = false;
                    }
                    columnNumber++;
                }
                gv.Width = k + width;
            }
 
        }
        catch(Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
    #endregion
}
로그인 후 복사


XmlHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Xml;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IsXMLUtility
{
   

    /// 
    ///XmlHelper 的摘要说明
    /// 
    public class XmlHelper
    {


        private string rtnXml;
        public XmlHelper()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
            rtnXml = string.Empty;
        }

        /// <summary>
        /// 获取xmltable
        /// </summary>
        /// <param name="xmlname">xml名字</param>
        /// <returns></returns>
        public DataTable getDTXML(string xmlname)
        {
            DataTable result = new DataTable();
            string fileName = HttpContext.Current.Request.PhysicalApplicationPath + "\\Xml\\" + xmlname + ".xml";//xml的物理路径
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNodeList xWitsTablesList = xmlDoc.SelectNodes("/config");
            foreach (XmlNode xOracleNode in xWitsTablesList)
            {
                foreach (XmlNode node2 in xOracleNode.ChildNodes)
                {
                    if (node2.Name == "Header")
                    {
                        //   //绑定表头
                        foreach (XmlNode node3 in node2.Attributes)
                        {
                            result.Columns.Add(node3.Value);
                        }
                    }
                    else
                    {
                        //数据行
                        int i = 0;//列标志
                        DataRow dr = result.NewRow();
                        foreach (XmlNode node4 in node2.Attributes)
                        {
                            dr[i] = node4.Value.ToString();
                            i++;
                        }
                        result.Rows.Add(dr);
                    }

                }
            }
            return result;
        }

        /// 
        /// 
        /// 
        /// xml名字
        /// 序号列名字
        /// 序号开始编号
        /// 
        public DataTable getDTXML(string xmlname, string Header, int colsNumber)
        {
            DataTable result = new DataTable();
            if (Header == "")
                Header = "N0";
            if (colsNumber < 0)
                colsNumber = 1;
            result.Columns.Add(Header);
            string fileName = HttpContext.Current.Request.PhysicalApplicationPath + "\\Xml\\" + xmlname + ".xml";//xml的物理路径
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNodeList xWitsTablesList = xmlDoc.SelectNodes("/config");
            foreach (XmlNode xOracleNode in xWitsTablesList)
            {
                foreach (XmlNode node2 in xOracleNode.ChildNodes)
                {
                    if (node2.Name == "Header")
                    {
                        //绑定表头
                        foreach (XmlNode node3 in node2.Attributes)
                        {
                            result.Columns.Add(node3.Value);
                        }
                    }
                    else
                    {
                        //数据行
                        int i = 1;//列标志
                        DataRow dr = result.NewRow();
                        dr[0] = colsNumber;
                        foreach (XmlNode node4 in node2.Attributes)
                        {
                            dr[i] = node4.Value.ToString();
                            i++;
                        }
                        colsNumber++;
                        result.Rows.Add(dr);
                    }

                }
            }
            return result;
        }



 


    }
}
로그인 후 복사

 以上就是xml学习(5)xml配置gridview列的内容,更多相关内容请关注PHP中文网(www.php.cn)! 

 

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿