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>
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 点击“添加”,然后在右边填写数据中的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"://查询 #region List<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) end GridView1.DataSource = gunList;//绑定数据源 GridView1.DataBind(); }//if (gunroot != null && gunroot.ChildNodes.Count > 0) end #endregion break; case "create"://增加 #region XmlElement 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);//保存文件并刷新当前页面 #endregion break; case "update"://修改 #region string 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 = ""; } #endregion break; default://删除 #region string conditionPath2 = "/gunbook/gun[@gid=\"" + commandAugument + "\"]";//XML获取节点的条件,格式固定,如果想要添加属性还可以用“and @属性=属性值” 操作 XmlNode deleteNode = xmldoc.SelectSingleNode(conditionPath2);//根据条件获取一个节点 if (deleteNode != null) {
deleteNode.ParentNode.RemoveChild(deleteNode);//移除当前节点 } SaveXML(xmldoc);//保存文件并刷新当前页面 #endregion break; } }//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", "");//绑定数据源 } } }
转载于:https://www.cnblogs.com/programsky/p/4620480.html
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/232694.html原文链接:https://javaforall.net
