C # Operations GridView Control Instance Tutorial

Source: Internet
Author: User
Tags foreach save file

What is a GridView control? This paragraph is from the Baidu Hundred: The GridView is the successor control of the DataGrid, in the. NET Framework 2, although there is a DataGrid, but the GridView has embarked on the historical front, the trend to replace the DataGrid is unstoppable. The GridView and DataGrid functions are similar in that they display data from a data source in a Web page, and a row of data from a data source, that is, a record, is displayed as a row in the output table on a Web page.


The data comes from an XML file, and if we don't know how to manipulate the XML data, we'll add it later.





1.XML content as follows:





--><?xml version= "1.0" encoding= "Utf-8"?>


<gunbook>


<gun type= "Automatic Rifle" gid= "001" >


<name>AK-47</name>


<from> Russia </from>


<clip>30</clip>


<accurate>0.2</accurate>


<range>300M</range>


</gun>


<gun type= "Sniper Gun" gid= "002" >


<name>AWM</name>


<from> UK </from>


<clip>10</clip>


<accurate>1</accurate>


<range>1000M</range>


</gun>


<gun type= "submachine gun" gid= "003" >


<name>MP5</name>


<from> USA </from>


<clip>80</clip>


<accurate>0.1</accurate>


<range>280M</range>


</gun>


<gun type= "Shotgun" gid= "004" >


<name> Hammer </name>


<from> Germany </from>


<clip>10</clip>


<accurate>0.2</accurate>


<range>120M</range>


</gun>


</gunbook>





(The data sources here can also be read from the database, such as "Select Uid,uname,usex,uage from Users" ...). So you don't have to use XML.











2. Defines a model class for easy data exchange:





Defines a gun's data model class


public class Gunmodel


{


Public Gunmodel () {}


The name of the gun


public string Gunname {get; set;}


Type of gun


public string Guntype {get; set;}


The number of the gun


public string Gunid {get; set;}


The origin of the gun


public string Gunfrom {get; set;}


The gun cartridge.


public string Gunclip {get; set;}


The accuracy of the gun


public string Gunaccurate {get; set;}


The range of the gun


public string Gunrange {get; set;}


}





-->

3. The front desk interface is as follows:


The above text box is textbox1-textbox7 from left to right respectively, the number is used as the primary key is therefore not editable, 3 buttons is also button1-button3,gridview1 is the current data control;


4.GridView Design

① drag a control from the toolbox to a Web page


② Click on the Small triangle button in the upper-right corner of the control and click Edit Column


③ add several boundfiled controls and a TemplateField control in the pop-up window, and remove the "auto-generated fields" in the lower-left corner of the window;


Note that the specific setting is--check boundfiled click "Add", and then fill in the DataField on the right (the name of the column in the data source, such as the current number Gunid), the HeaderText in the skin (the name of the column to display on the page, for example, the current number),

TemplateField only need to fill in the HeaderText, and then cancel the "Automatically generated fields" check box, and finally click "OK";

④ Click "AutoFormat" Can be set according to the appropriate style, click "Edit Template" for the operation of the template settings


Drag two LinkButton, edit and delete names separately (LinkButton property Font-->underline Select False to underline, but 2 to enable this action)


⑤ edit Post interface as follows


⑥ the relevant settings for the foreground interface


Note: CommandArgument can bind to the corresponding value on the current control, generally we are bound to the value of the primary key column, such as the Gunid here (not partition case); CommandName is to facilitate the background through the GridView Rowcommand event to find the type of the current operation, such as edit or delete, notice the name must avoid keywords, such as "edit", "Update", "delete", you can Play "upd", " Del "and so on; OnClientClick is generally used in front of the frame events, such as the deletion tips here.

In addition, the control's property allowpaging=true can be paginated, and the PageSize property can set the paging size, that is, the number of displays per page.







5. Background Code





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", "");


}


}





Inquire


protected void Button1_Click (object sender, EventArgs e)


{


Operationxml ("Select", "");


}





Add to


protected void button2_click (object sender, EventArgs e)


{


Change the style of a control in the background


BUTTON2.ATTRIBUTES.ADD ("Style", "background-color:red;"); /This is mode 1, follow the CSS style to change


BUTTON2.STYLE.ADD ("Color", "Blue");//This is mode 2, changing with the control's own properties





if (TextBox1.Text.Trim () = = "")//number must exist


{


Response.Write (' </p><script>alert (please fill in to add Data ') </script><p> ");


Return


}


Operationxml ("Create", "");


Clearcontrol ()//Empty text box


}





Modify


protected void Button3_Click (object sender, EventArgs e)


{


if (TextBox1.Text.Trim () = = "")//number must exist


{


Response.Write ("</p><script>alert" click Edit on the line you want to modify and try again!) ') </script><p> ");


Return


}





XmlDocument xmldoc = new XmlDocument ();//Add an XML Document object


XmlDoc. Load (Getxmlpath ());//Loading document





XmlNode gunroot = xmldoc. selectSingleNode ("Gunbook");//Get root node


String Conditionpath = "/gunbook/gun[@gid =\" "+ TextBox1.Text +" \ "]"//xml get the condition of the node, the format is fixed, if you want to add a property can also use the "and @ Property = property value" Action


XmlNode Updatenode = xmldoc. selectSingleNode (Conditionpath)//Get a node according to the condition





if (Updatenode!= null && updatenode.childnodes!= null && updateNode.ChildNodes.Count = 5)


{


UpdateNode.ChildNodes.Item (0). innertext = textbox2.text;//Name


UpdateNode.Attributes.GetNamedItem ("type"). innertext = textbox3.text;//Type


UpdateNode.ChildNodes.Item (1). InnerText = textbox4.text;//Origin


UpdateNode.ChildNodes.Item (2). InnerText = textbox5.text;//Cartridge


UpdateNode.ChildNodes.Item (3). innertext = textbox6.text;//Precision


UpdateNode.ChildNodes.Item (4). innertext = textbox7.text;//Range


}





SaveXML (xmldoc);//save file and Refresh current page





Clearcontrol ()//Empty text box


}





///


Empty control values
///


private void Clearcontrol ()
{
TextBox1.Text = TextBox2.Text = TextBox3.Text = Textbox4.text = Textbox5.text = Textbox6.text = TextBox7.Text = "";
}

///


///The public method of manipulating XML classes

Response.Write ("<script>alert" ("+ +") </script>);

        ///


Action type name, Select/create/update/delete


Operation parameters, where the primary key is passed in Gunid


private void Operationxml (String opname,string commandaugument)


{


XmlDocument xmldoc = new XmlDocument ();//Add an XML Document object


XmlDoc. Load (Getxmlpath ());//Loading document





XmlNode gunroot = xmldoc. selectSingleNode ("Gunbook");//Get root node





Switch (opname)


{


Case "SELECT"://Query


#region





List

Gunlist = new List ()//define a set of guns


if (gunroot!= null &amp;&amp; gunroot. Childnodes.count &gt; 0)


{


XmlNodeList childlist;


foreach (XmlNode child in Gunroot.) ChildNodes)//loops all child nodes


{


First, get the value of the property directly through the XmlNode


String type = child. Attributes.getnameditem ("type"). InnerText;


String id = child. Attributes.getnameditem ("GID"). InnerText;





Second, get the value of the property through 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 &amp;&amp; childlist.count = 5)


{


Gunmodel. Gunname = Childlist.item (0). innertext;//Name


Gunmodel. Gunfrom = Childlist.item (1). innertext;//origin


Gunmodel. Gunclip = Childlist.item (2). innertext;//Magazine.


Gunmodel. Gunaccurate = Childlist.item (3). innertext;//Accurate


Gunmodel. Gunrange = Childlist.item (4). innertext;//Range


}


Else


{


Gunmodel. Gunname = "no data";


Gunmodel. Gunfrom = "no data";


Gunmodel. Gunclip = "no data";


Gunmodel. Gunaccurate = "no data";


Gunmodel. Gunrange = "no data";


}





Gunlist.add (Gunmodel)//Add the gun object to the gun collection


}//foreach (XmlNode child in Gunroot.) ChildNodes) End





Gridview1.datasource = gunlist;//bound data source


Gridview1.databind ();





}//if (gunroot!= null &amp;&amp; gunroot. Childnodes.count &gt; 0) End





#endregion


Break





Case "Create"://Increase


#region





XmlElement createelement = xmldoc. CreateElement ("gun");//Create a gun node element


Createelement.setattribute ("type", textbox3.text);//Type


Createelement.setattribute ("GID", textbox1.text);/number


XmlNode CreateNode = (XmlNode) createelement;


Gunroot. AppendChild (CreateNode);





XmlElement createelementchildname = xmldoc. createelement ("name");//Name


Createelementchildname.innertext = textbox2.text;//Value


Createelement.appendchild (Createelementchildname);





XmlElement createelementchildfrom = xmldoc. CreateElement ("from")/origin


Createelementchildfrom.innertext = textbox4.text;//Value


Createelement.appendchild (Createelementchildfrom);





XmlElement createelementchildclip = xmldoc. createelement ("clip");/magazine


Createelementchildclip.innertext = textbox5.text;//Value


Createelement.appendchild (Createelementchildclip);





XmlElement createelementchildaccurate = xmldoc. createelement ("accurate")/accurate


Createelementchildaccurate.innertext = textbox6.text;//Value


Createelement.appendchild (createelementchildaccurate);





XmlElement createelementchildrange = xmldoc. CreateElement ("range");/Range


Createelementchildrange.innertext = textbox7.text;//Value


Createelement.appendchild (Createelementchildrange);





SaveXML (xmldoc);//save file and Refresh current page





#endregion


Break





Case "Update"://Modify


#region





String Conditionpath = "/gunbook/gun[@gid =\" "+ commandaugument +" \ "]"//xml get the condition of the node, the format is fixed, if you want to add a property can also use the "and @ Property = property value" Action


XmlNode Updatenode = xmldoc. selectSingleNode (Conditionpath)//Get a node according to the condition


TextBox1.Text = commandaugument;//Number


if (Updatenode!= null &amp;&amp; updatenode.childnodes!= null &amp;&amp; updateNode.ChildNodes.Count = 5)


{


TextBox2.Text = UpdateNode.ChildNodes.Item (0). innertext;//Name


TextBox3.Text = UpdateNode.Attributes.GetNamedItem ("type"). innertext;//type


Textbox4.text = UpdateNode.ChildNodes.Item (1). innertext;//origin


Textbox5.text = UpdateNode.ChildNodes.Item (2). innertext;//Magazine.


Textbox6.text = UpdateNode.ChildNodes.Item (3). innertext;//Accurate


Textbox7.text = UpdateNode.ChildNodes.Item (4). innertext;//Range


}


Else


{


TextBox2.Text = "";


TextBox3.Text = "";


Textbox4.text = "";


Textbox5.text = "";


Textbox6.text = "";


Textbox7.text = "";


}





#endregion


Break





default://Delete


#region





String conditionPath2 = "/gunbook/gun[@gid =\" "+ commandaugument +" \ "]"//xml get the condition of the node, the format is fixed, if you want to add a property can also use the "and @ Property = property value" Action


XmlNode Deletenode = xmldoc. selectSingleNode (conditionPath2)//Get a node according to the condition





if (Deletenode!= null)


{


DeleteNode.ParentNode.RemoveChild (Deletenode);//Remove current node


}





SaveXML (xmldoc);//save file and Refresh current page





#endregion


Break


}








}//function End





///
Get XML file path
///


///


private String Getxmlpath ()


{


String xmlpath = Server.MapPath ("Gun.xml");


return xmlpath;


}





///
Save XML file
///


/// XML file name


private void SaveXML (XmlDocument xmldoc)


{


XmlDoc. Save (Getxmlpath ());


Operationxml ("Select", "")//Refresh Page


}





protected void Gridview1_rowcommand (object sender, Gridviewcommandeventargs e)


{


if (E.commandname = = "UPD")//Edit


{


textbox1.enabled = false;//number cannot be edited, otherwise loss of primary key meaning


String guid = E.commandargument.tostring ();





Operationxml ("Update", e.commandargument.tostring ());





GridViewRow GVR = (GridViewRow) ((LinkButton) (E.commandsource). parent.parent);//The current control is in the row


Int J = Gvr. rowindex;//the Index of the current control's row, where


}


else//del, deleting


{


Operationxml ("Delete", e.commandargument.tostring ());


}


}





Paging


protected void Gridview1_pageindexchanging (object sender, Gridviewpageeventargs e)


{


Gridview1.pageindex = E.newpageindex;


Operationxml ("Select", "");//bound data source


}





}


}








C # Operations XML document Instance tutorial





An XML document is a generic document that can use. config as a suffix or. xml as a suffix. XML documents are composed primarily of element nodes and the attributes of nodes. It has and only one root node, the other nodes are all the root node of the child nodes or child nodes; Each node has a beginning must have the end, there is no beginning to end the node, there are two main types of nodes: there are innertext ..... And no innertext. 。 With attributes in a node, a node can contain multiple attributes, each of which is composed of a name and a value.





In XML documents, nodes, attributes are case-sensitive. For a node's properties, name cannot be duplicated, even when defining a property, two name identical attributes are added to the same node, and subsequent attributes overwrite the preceding attribute without reporting a syntax error; for a child node under a node, You can add more than one child node that is exactly the same.





The prerequisite for an operation on an XML document is that the XML document already exists and the root node already exists.





first, add nodes and properties





1. Define an XML Action object:





XmlDocument doc = new XmlDocument ();





2. Load an XML file:





Doc. Load (@ "D:\App.config");





The specified file must exist or it will be an error.





3. Get root node:





XmlNode root = Doc. DocumentElement;





4. Define an attribute:





XmlAttribute RA = doc. CreateAttribute ("Name");





5. Assigning values to attributes:





Ra. Value = "Zwj2";





6, add the attribute to the node above:





Root. Attributes.append (RA);





7, and then define a node as the root node of the child node:





XmlNode root1 = doc. createelement ("table");





8. Assigning text values to nodes:





Root1. innertext = "SDF1";





9. Define and add attributes to the node





10, add the node to the parent node:





Root. AppendChild (ROOT1);





11. Save XML Document:





Doc. Save (@ "D:\App.config");





Note: You can add multiple properties to a node, and then each property will be sorted back in order, you can add multiple child nodes to the root node, or you can cadogan the child nodes to the node.





ii. querying and modifying nodes and attributes





1, the element node has the name attribute, is the &lt;&gt; inside string, also has the innertext attribute (corresponds to the text knot point), is the &lt;&gt;&lt;/&gt; between the string: root. Name, Root. InnerText. These properties are both read and write. ------------------------------XmlNode





2, the property node has name, also has Value:providername= "System.Data.SqlClient", preceded by name, followed by value these properties can be read or write. -----------------------------------------------------------XmlAttribute





3. Each node has a set of child nodes, as well as a set of attributes: root. ChildNodes, Root. The Attributes collection has the Count property.





4, the collection is satisfied with the index:





For a collection of attributes, the name of the property cannot be duplicated, so the index can be a name string index, the name string exists, otherwise a Null Property object is returned, no error is available, or an integer index, then the integer cannot be crossed, otherwise it will be an error;: Root. attributes["name", Root. Attributes[0], return to XmlAttribute.





For a collection of child nodes, because the child nodes can be exactly the same, the name of the child node can certainly be the same, so the index can only be an integer, not the child node name string, the integer index can not cross the line, or it will be an error: root. CHILDNODES[10], return to XmlNode.





three, several important functions





1, XmlNode Xmldocument.selectsinglenode (@ "Configuration/twonode/daystart")





This function calls the selectSingleNode function with a XmlDocument object that is declared well and has successfully loaded a configuration file, and the parameter of the function is the name of the configuration file from the root node name down to the desired node. The entire name path cannot be faulted, note is a left slash; the return value of the function is the object of the first XmlNode node found and returns null if it is not found.





Manipulate the following XML:





&lt;?xmlversion= "1.0"?&gt;





&lt;configuration&gt;





&lt;twoNode&gt;





&lt;/twoNode&gt;





&lt;twoNode&gt;





&lt;dayStart&gt;1&lt;/dayStart&gt;





&lt;dayStart&gt;2&lt;/dayStart&gt;





&lt;dayStart&gt;3&lt;/dayStart&gt;





&lt;/twoNode&gt;





&lt;/configuration&gt;





If you execute this function, you will find the node:&lt;daystart&gt;1&lt;/daystart&gt;





2, XmlNodeList xmldocument.selectnodes (@ "Configuration/twonode/daystart")





This function calls the SelectNodes function with a XmlDocument object that is declared well and has successfully loaded a configuration file, and the parameter of the function is the name of the configuration file from the root node name down to the desired node, and the entire name path cannot be faulted. Note that the left slash is, because the name of the node is likely to be duplicated, so the return value of the function is the collection of all the XmlNode node objects found XmlNodeList and returns null if it is not found.





XmlNodeList is a collection, then there is the Count property, you can directly to the collection with [int index] to index the specific object, you can also use the Set item (int index) function to index the specific object, but the index can not cross, otherwise there will be errors, The return is XmlNode.





Manipulate the following XML:





&lt;?xmlversion= "1.0"?&gt;





&lt;configuration&gt;





&lt;twoNode&gt;





&lt;dayStart&gt;-1&lt;/dayStart&gt;





&lt;dayStart&gt;-2&lt;/dayStart&gt;





&lt;dayStart&gt;-3&lt;/dayStart&gt;





&lt;/twoNode&gt;





&lt;twoNode&gt;





&lt;dayStart&gt;1&lt;/dayStart&gt;





&lt;dayStart&gt;2&lt;/dayStart&gt;





&lt;dayStart&gt;3&lt;/dayStart&gt;





&lt;/twoNode&gt;





&lt;/configuration&gt;





If this function is executed, the node collection will be found:





&lt;dayStart&gt;-1&lt;/dayStart&gt;





&lt;dayStart&gt;-2&lt;/dayStart&gt;





&lt;dayStart&gt;-3&lt;/dayStart&gt;





&lt;dayStart&gt;1&lt;/dayStart&gt;





&lt;dayStart&gt;2&lt;/dayStart&gt;





&lt;dayStart&gt;3&lt;/dayStart&gt;











Manipulate the following XML:





&lt;?xmlversion= "1.0"?&gt;





&lt;configuration&gt;





&lt;twoNode&gt;





&lt;/twoNode&gt;





&lt;twoNode&gt;





&lt;dayStart&gt;1&lt;/dayStart&gt;





&lt;dayStart&gt;2&lt;/dayStart&gt;





&lt;dayStart&gt;3&lt;/dayStart&gt;





&lt;/twoNode&gt;





&lt;/configuration&gt;





If this function is executed, the node collection will be found:





&lt;dayStart&gt;1&lt;/dayStart&gt;





&lt;dayStart&gt;2&lt;/dayStart&gt;





&lt;dayStart&gt;3&lt;/dayStart&gt;





Let's start with the actual operation!





A. Add an XML file named Book.xml, which reads as follows:








&lt;?xml version= "1.0" encoding= "Utf-8"?&gt;


&lt;bookstore&gt;


&lt;book type= "Compulsory course" isbn= "7-111-19149-2" &gt;


&lt;title&gt; Data Structure &lt;/title&gt;


&lt;author&gt; Min &lt;/author&gt;


&lt;price&gt;30.00&lt;/price&gt;


&lt;/book&gt;


&lt;book type= "Compulsory course" isbn= "7-111-19149-3" &gt;


&lt;title&gt; Routing and Exchange-based Internet &lt;/title&gt;


&lt;author&gt; Cheng Qingmei &lt;/author&gt;


&lt;price&gt;27.00&lt;/price&gt;


&lt;/book&gt;


&lt;book type= "Compulsory course" isbn= "7-111-19149-4" &gt;


&lt;title&gt; Computer hardware Technology base &lt;/title&gt;


&lt;author&gt; Li Jizan &lt;/author&gt;


&lt;price&gt;25.00&lt;/price&gt;


&lt;/book&gt;


&lt;book type= "Compulsory course" isbn= "7-111-19149-5" &gt;


&lt;title&gt; Software Quality assurance and management &lt;/title&gt;


&lt;author&gt; Zhu Shaomin &lt;/author&gt;


&lt;price&gt;39.00&lt;/price&gt;


&lt;/book&gt;


&lt;book type= "Compulsory course" isbn= "7-111-19149-6" &gt;


&lt;title&gt; algorithm design and Analysis &lt;/title&gt;


&lt;author&gt; Wang &lt;/author&gt;


&lt;price&gt;23.00&lt;/price&gt;


&lt;/book&gt;


&lt;book type= "Elective" isbn= "7-111-19149-1" &gt;


&lt;title&gt; Computer operating System &lt;/title&gt;


&lt;author&gt; you guess &lt;/author&gt;


&lt;price&gt;28&lt;/price&gt;


&lt;/book&gt;


&lt;/bookstore&gt;


Two. Add a Web page, named Xml_operation.aspx, with the following page contents:

A total of 4 buttons, namely Button1, Button2, Button3, Button4, and then a GridView1 to display the data



Three. Add a BookModel.cs class to read the data as follows:


public class Bookmodel
{
Constructors
Public Bookmodel () {}

///


The corresponding course type
///


public string BookType {get; set;}

///


The ISBN number corresponding to the book
///


public string BOOKISBN {get; set;}

///


Title
///


public string BookName {get; set;}

///


Author
///


public string Bookauthor {get; set;}

///


Price
///




public string Bookprice {get; set;}


}














four. The background code is as follows:





1. Add namespaces using System.Xml;





2. Add a public method to manipulate the current XML





In addition, if you want to get an XML relative path, you can do this by referencing the namespace using System.IO first; Then direct stirng Xmlpath = Server.MapPath ("Gun.xml").











3. The individual invocation events are as follows:








Query node


protected void Button1_Click (object sender, EventArgs e)


{


Operationxml ("select");


}





New node


protected void button2_click (object sender, EventArgs e)


{


Operationxml ("create");


}





modifying nodes


protected void Button3_Click (object sender, EventArgs e)


{


Operationxml ("Update");


}





Delete a node


protected void Button4_Click (object sender, EventArgs e)


{


Operationxml ("delete");


}









Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.