GridView控件是一个visualStudio自带的数据控件,它可以非常快速的将数据以表格方式显示在web页面上。下面就是一个利用GridView控件进行数据绑定的小例子,内容如下:

数据来源自一个XML文件,至于如何操作XML文件,这里不作详细描述,具体可以参考 http://www.cnblogs.com/programsky/p/3816073.html

1.XML内容如下:

<?xml version="1.0" encoding="utf-8"?>
<gunbook><gun type="自动步枪" gid="001"><name>AK-47</name><from>俄罗斯</from><clip>30</clip><accurate>0.2</accurate><range>300M</range></gun><gun type="狙击枪" gid="002"><name>AWM</name><from>英国</from><clip>10</clip><accurate>1</accurate><range>1000M</range></gun><gun type="冲锋枪" gid="003"><name>MP5</name><from>美国</from><clip>80</clip><accurate>0.1</accurate><range>280M</range></gun><gun type="霰弹枪" gid="004"><name>气锤</name><from>德国</from><clip>10</clip><accurate>0.2</accurate><range>120M</range></gun>
</gunbook>

View Code
(这里的数据源还可以从数据库中读取,比如“select uid,uname,usex,uage from users”…这样就可以不用XML了)

2.定义了一个model类便于数据交换:

//定义一个枪的数据模型类

   public class GunModel{public GunModel() { }//枪的名称public string GunName { get; set; }//枪的类型public string GunType { get; set; }//枪的编号public string GunID { get; set; }//枪的产地public string GunFrom { get; set; }//枪的弹夹public string GunClip { get; set; }//枪的精准度public string GunAccurate { get; set; }//枪的射程public string GunRange { get; set; }}

View Code

3.前台界面如下:

上面的文本框从左到右分别是TextBox1-TextBox7,编号是用来作为主键的因此不可编辑,3个按钮亦是Button1-Button3,GridView1是当前数据控件;

4.GridView设计

①从工具箱拖一个控件到web页面

②点击控件右上角的小三角按钮,然后点击“编辑列”

③在弹出窗口中分别添加若干BoundFiled控件和一个TemplateField控件,并去掉窗口左下角的“自动生成字段”即不勾选;

注意,具体设置是——选中 BoundFiled 点击“添加”,然后在右边填写数据中的DataField(数据源中的列名,例如当前的编号GunID)、外观中的HeaderText(要显示在页面上的列名,例如当前的“编号”),

TemplateField只需要填写HeaderText即可,然后取消“自动生成字段”的勾选框,最后点击“确定”;

④点击“自动套用格式”可以根据需要设置相应的样式,点击“编辑模板”进行操作中的模板设置

拖两个LinkButton,分别起名称 编辑 、 删除 (LinkButton属性Font–>UnderLine选择False可以去掉下划线,不过要选2下才能启用此操作)

⑤编辑后界面如下

⑥进行前台界面的相关设置

注意:CommandArgument可以绑定当前控件上的相应值,一般我们都是绑定主键列的值,例如这里的GunID(不分区大小写);CommandName是为了方便后台通过GridView的RowCommand事件找到当前操作的类型,比如编辑或是删除,注意起名字一定要避免关键字,如"edit"、“update”、“delete”,可以起"upd"、"del"等;OnClientClick一般用于前台的弹框事件,比如这里的删除提示。

另外,控件的属性AllowPaging=true 可以进行分页,而PageSize属性可以设置分页大小,即每页显示的数量。

5.后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;using System.Xml;
using System.IO;namespace AboutXML
{public partial class Gun : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){TextBox1.Enabled = true;if (!Page.IsPostBack) {OperationXML("select", "");}}        //查询protected void Button1_Click(object sender, EventArgs e){OperationXML("select", "");}//添加protected void Button2_Click(object sender, EventArgs e){//在后台改变控件的样式//Button2.Attributes.Add("style", "background-color:red;");//这是方式1,按照Css的样式进行改变//Button2.Style.Add("Color", "blue");//这是方式2,按照控件自带属性进行改变if (TextBox1.Text.Trim() == "") //编号必须存在{Response.Write("<script>alert('请填写要添加数据')</script>");return;}OperationXML("create", "");ClearControl();//清空文本框}//修改protected void Button3_Click(object sender, EventArgs e){if (TextBox1.Text.Trim() == "") //编号必须存在{Response.Write("<script>alert('请在要修改的行上点击“编辑”后重试!')</script>");return;}XmlDocument xmldoc = new XmlDocument();//添加一个xml文档对象xmldoc.Load(GetXMLPath());//加载文档XmlNode gunroot = xmldoc.SelectSingleNode("gunbook");//获取根节点string conditionPath = "/gunbook/gun[@gid=\"" + TextBox1.Text + "\"]";//XML获取节点的条件,格式固定,如果想要添加属性还可以用“and @属性=属性值” 操作XmlNode updateNode = xmldoc.SelectSingleNode(conditionPath);//根据条件获取一个节点if (updateNode != null && updateNode.ChildNodes != null && updateNode.ChildNodes.Count == 5){updateNode.ChildNodes.Item(0).InnerText = TextBox2.Text;//名称updateNode.Attributes.GetNamedItem("type").InnerText = TextBox3.Text;//类型updateNode.ChildNodes.Item(1).InnerText = TextBox4.Text;//产地updateNode.ChildNodes.Item(2).InnerText = TextBox5.Text;//弹夹updateNode.ChildNodes.Item(3).InnerText = TextBox6.Text;//精准updateNode.ChildNodes.Item(4).InnerText = TextBox7.Text;//射程}SaveXML(xmldoc);//保存文件并刷新当前页面ClearControl();//清空文本框}/// <summary>/// 清空控件值/// </summary>private void ClearControl() {TextBox1.Text = TextBox2.Text = TextBox3.Text = TextBox4.Text = TextBox5.Text = TextBox6.Text = TextBox7.Text = "";}/// <summary>/// 操作XML类的公共方法 Response.Write("<script>alert('"++"')</script>");/// </summary>/// <param name="opname">操作类型名称,select/create/update/delete</param>/// <param name="commandAugument">操作参数,这里传入的是主键gunid</param>private void OperationXML(string opname,string commandAugument) {XmlDocument xmldoc = new XmlDocument();//添加一个xml文档对象xmldoc.Load(GetXMLPath());//加载文档XmlNode gunroot = xmldoc.SelectSingleNode("gunbook");//获取根节点switch (opname) {case "select"://查询#regionList<GunModel> gunList = new List<GunModel>();//定义一个枪的集合if (gunroot != null && gunroot.ChildNodes.Count > 0){XmlNodeList childList;foreach (XmlNode child in gunroot.ChildNodes)//循环所有子节点{//第一种,直接通过XmlNode获取属性值string type = child.Attributes.GetNamedItem("type").InnerText;string id = child.Attributes.GetNamedItem("gid").InnerText;//第二种,通过XmlElement获取属性值//XmlElement xmlatt = (XmlElement)child;//string type = xmlatt.GetAttribute("type");//string id = xmlatt.GetAttribute("gid");GunModel gunmodel = new GunModel();gunmodel.GunType = type;gunmodel.GunID = id;childList = child.ChildNodes;if (childList != null && childList.Count == 5){gunmodel.GunName = childList.Item(0).InnerText;//名称gunmodel.GunFrom = childList.Item(1).InnerText;//产地gunmodel.GunClip = childList.Item(2).InnerText;//弹夹gunmodel.GunAccurate = childList.Item(3).InnerText;//精准gunmodel.GunRange = childList.Item(4).InnerText;//射程}else {gunmodel.GunName = "no data";gunmodel.GunFrom = "no data";gunmodel.GunClip = "no data";gunmodel.GunAccurate = "no data";gunmodel.GunRange = "no data";}gunList.Add(gunmodel);//将枪对象添加到枪集合中}//foreach (XmlNode child in gunroot.ChildNodes) endGridView1.DataSource = gunList;//绑定数据源GridView1.DataBind();}//if (gunroot != null && gunroot.ChildNodes.Count > 0) end#endregionbreak;case "create"://增加#regionXmlElement createElement = xmldoc.CreateElement("gun");//创建一个枪的节点元素createElement.SetAttribute("type", TextBox3.Text);//类型createElement.SetAttribute("gid", TextBox1.Text);//编号XmlNode createNode = (XmlNode)createElement;gunroot.AppendChild(createNode);//XmlElement createElementChildName = xmldoc.CreateElement("name");//名称createElementChildName.InnerText = TextBox2.Text;//值createElement.AppendChild(createElementChildName);XmlElement createElementChildFrom = xmldoc.CreateElement("from");//产地createElementChildFrom.InnerText = TextBox4.Text;//值createElement.AppendChild(createElementChildFrom);XmlElement createElementChildClip = xmldoc.CreateElement("clip");//弹夹createElementChildClip.InnerText = TextBox5.Text;//值createElement.AppendChild(createElementChildClip);XmlElement createElementChildAccurate = xmldoc.CreateElement("accurate");//精准createElementChildAccurate.InnerText = TextBox6.Text;//值createElement.AppendChild(createElementChildAccurate);XmlElement createElementChildRange = xmldoc.CreateElement("range");//射程createElementChildRange.InnerText = TextBox7.Text;//值createElement.AppendChild(createElementChildRange);SaveXML(xmldoc);//保存文件并刷新当前页面#endregionbreak;case "update"://修改#regionstring conditionPath = "/gunbook/gun[@gid=\"" + commandAugument + "\"]";//XML获取节点的条件,格式固定,如果想要添加属性还可以用“and @属性=属性值” 操作XmlNode updateNode = xmldoc.SelectSingleNode(conditionPath);//根据条件获取一个节点TextBox1.Text = commandAugument;//编号if (updateNode != null && updateNode.ChildNodes != null && updateNode.ChildNodes.Count == 5){TextBox2.Text = updateNode.ChildNodes.Item(0).InnerText;//名称TextBox3.Text = updateNode.Attributes.GetNamedItem("type").InnerText;//类型TextBox4.Text = updateNode.ChildNodes.Item(1).InnerText;//产地TextBox5.Text = updateNode.ChildNodes.Item(2).InnerText;//弹夹TextBox6.Text = updateNode.ChildNodes.Item(3).InnerText;//精准TextBox7.Text = updateNode.ChildNodes.Item(4).InnerText;//射程}else {TextBox2.Text = "";TextBox3.Text = "";TextBox4.Text = "";TextBox5.Text = "";TextBox6.Text = "";TextBox7.Text = "";}#endregionbreak;default://删除#regionstring conditionPath2 = "/gunbook/gun[@gid=\"" + commandAugument + "\"]";//XML获取节点的条件,格式固定,如果想要添加属性还可以用“and @属性=属性值” 操作XmlNode deleteNode = xmldoc.SelectSingleNode(conditionPath2);//根据条件获取一个节点if (deleteNode != null) {deleteNode.ParentNode.RemoveChild(deleteNode);//移除当前节点}SaveXML(xmldoc);//保存文件并刷新当前页面#endregionbreak;}}//function end/// <summary>/// 获取xml文件路径/// </summary>/// <returns></returns>private string GetXMLPath() {string xmlPath = Server.MapPath("Gun.xml");return xmlPath;}/// <summary>/// 保存XML文件/// </summary>/// <param name="xmldoc">xml文件名称</param>private void SaveXML(XmlDocument xmldoc) {xmldoc.Save(GetXMLPath());OperationXML("select", "");//刷新页面}protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e){if (e.CommandName == "upd")//编辑{TextBox1.Enabled = false;//编号不能编辑,否则失去主键意义string guid = e.CommandArgument.ToString();OperationXML("update", e.CommandArgument.ToString());//GridViewRow gvr = (GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent);//当前控件所在行//int j = gvr.RowIndex;//当前控件所在行的 Index,即行的位置}else //del,删除{OperationXML("delete",e.CommandArgument.ToString());}}//分页protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e){GridView1.PageIndex = e.NewPageIndex;OperationXML("select", "");//绑定数据源}}
}

View Code
当然,这里的查询还可以按照条件来,只不过我这里没有实现,有兴趣可以自己试试。

转载于:https://www.cnblogs.com/programsky/p/4620480.html

C#中 GridView控件的使用相关推荐

  1. C#中GridView控件的使用

    C#中GridView控件的使用 一.GridView和DataGrid的异同 GridView 是 DataGrid的后继控件,在 framework 2中,虽然还存在DataGrid,但是Grid ...

  2. asp.net 中GridView控件实现全选及反选的功能

    大家都知道邮箱里面有全部删除邮件的复选按钮,其实还是比较简单哈! 废话嘛!就不说那么多了,我先给大家讲哈功能的实现. 首先,拖一个GridView控件和SqlDataSource控件,配置数据源. 然 ...

  3. 测试ASP.NET 2.0中Gridview控件高级技巧

    ASP.NET 2.0中,新增加的gridview控件的确十分强大,弥补了在asp.net 1.1中,使用datagrid控件时的不足之处.因为在asp.net 1.1中,在使用datagrid时,很 ...

  4. WebForm中GridView控件中添加一列按钮实现跳转传参

    在ToolBox中拖动GridView控件 点击箭头编辑Columns 双击添加HyperLinkField 具体设置properties 还可以使用代码编写 <asp:HyperLinkFie ...

  5. 使用ASP.NET 2.0中的GridView控件

    在ASP.NET 2.0中,加入了许多新的功能和控件,相比asp.net 1.0/1.1,在各方面都有了很大的提高.其中,在数据控件方面,增加了不少控件,其中的gridview控件功能十分强大.在本文 ...

  6. GridView控件常见问题及处理方法

    Asp.net 1.1版本中的DataGrid控件用于显示表格式的数据,相信大家都用过.Asp.net 2.0版本中GridView控件是DataGrid控件的继承者,功能比DataGrid增强不少, ...

  7. .net dataGridView当鼠标经过时当前行背景色变色;然后【给GridView增加单击行事件,并获取单击行的数据填充到页面中的控件中】...

    1.首先在前台dataGridview属性中增加onRowDataBound属性事件 2.然后在后台Observing_RowDataBound事件中增加代码 protected void Obser ...

  8. 在 GridView 控件中添加一列复选框51

    简介 在前面的教程中 , 我们学习了如何为 GridView 控件添加一列 单选 按钮来选择一个特定的记录.当用户被限制最多只能从网格中选中一项时,一列单选按钮是一个非常恰当的用户界面.然而,有时我们 ...

  9. 寻找GridView中模板列中的控件

    假如你在gridview中添加一个模板列,并 在模板列中存放了一个dropdownlist控件.那么,问题就是:你如何去操作这个dropdownlist控件???? //对于gridview控件:  ...

最新文章

  1. Save could not be completed. Eclipse国际化的问题解决
  2. STL容器是否是线程安全的
  3. python 模拟抽象类
  4. 关于计算机应用技术的周记,计算机应用技术专业实习周记范文
  5. hadoop-1.1.2 在centos环境下的部署
  6. Xcode没有pch文件
  7. Linux内核编译和运行
  8. Redis 实践笔记1---基础知识
  9. ASP.NET Core 日志框架:Serilog
  10. 使用Spring WebFlux进行操作
  11. Python自动化测试|如何解决前置模块及数据依赖(二)
  12. (42)Xilinx FIFO IP核配置(三)(第9天)
  13. NFrog[NHibernate代码工具]发布第一个版本
  14. 海量ICLR论文点评公开,用这几个工具可以读得更轻松
  15. 数据预测之BP神经网络具体应用以及matlab代码
  16. 西安电子科技大学计算机学院数据结构真题,数据结构1800题(标准答案全)
  17. DevOps落地实践:通讯行业系列:NTT COMWARE之Devaas
  18. 废掉一个人最隐蔽的方式,是让他忙到没时间成长
  19. 浅谈数据监控数据分析
  20. Biblatex 参考文献样式

热门文章

  1. addEventListener和removeEventListener
  2. 第十七期 U-Boot norflash 操作原理分析 《路由器就是开发板》
  3. ADM(架构开发方法)
  4. jsp和MySQL实现会员卡功能_健身房会员卡管理系统的设计与实现(JSP,MySQL)(含录像)...
  5. 【android应用】常用色彩模式ARGB详解
  6. 未来教育的五大赛道解析推理
  7. 西北工业大学计算机学硕复试,分享:西北工业大学计算机考研复试经验_跨考网...
  8. 中毒U盘恢复--快捷键病毒
  9. js监听手机端的touch滑动事件
  10. iOS开发:苹果2018最新款手机(iPhone XS Max、iPhone XR等)如何查看并获取手机的UDID