How to make all the rows of the DataGrid editable

Source: Internet
Author: User
Tags xml example
<% @ Import Namespace = "System. data "%> <% @ Import Namespace =" System. data. sqlClient "%> 
Top
Reply:Coolmars (mars)() Credit: 100 2003-07-25 16: 14: 44Z Score: 0
?
Nxyc_twz@163.com in the Forum I have seen many identical or similar problems: how do I place check boxes and text boxes in each row of my DataGrid? How to update their values? The answer is quite simple. In this article, I will show you how to complete it. We all know that DataGrid is a very powerful tool. In my experience, in more than 90% of the time, DataGrid is used to display data and may edit a row of data at a time. In some cases, you may need to edit multiple rows or even all data at a time. In an actual example, in an app that sells items online, a customer may want to change one or more items in their basket at a time, and click the check box to move the items they do not want. In this example, I wrote a simple WebForm to manage the contact list stored in XML. This requirement is very simple: with the ability to add new contacts, edit/delete existing contacts. Users can modify or delete multiple contacts at a time. I also allow users to sort data grids by their selected columns. My example is written in C. If you prefer the VB version of the Code, there are two formats of code in the downloaded file. In the Contacts. xml example, the XML data file is very simple and intuitive. Because it is very simple, I did not create a plan. <? Xml version = "1.0" standalone = "yes"?> <Contacts> <Contact> <Email> myaddress@mycompany.com </Email> <FirstName> John </FirstName> <LastName> Doe </LastName> </Contact> <Email> youraddress@yourcompany.com </Email> <FirstName> Jane </FirstName> <LastName> Doe </LastName> </Contact> </Contacts> ContactList. aspx setting WebForm is very simple. I placed a new DataGrid in my form and set it to four columns. The first column contains the check box used to delete contacts. You will notice that my main task here is to create each column in the form of a template column (TemplateColumn. This allows me to place text boxes and check box objects into the data template (ItemTemplate). This is a trick to show anything other than text in each row of the grid. In addition, you will also notice that I use FooterTemplate to make new contacts simple and intuitive. I also include a link button to save your modifications and delete operations. But it is not used to add new contacts. The link button in the footer template of the last column is used to add a new contact. <Asp: datagrid id = "dgContacts" runat = "server" ShowFooter = "True" AllowSorting = "True" Forefont color = "Black" GridLines = "None" CellPadding = "2" Backfont color = "inline" BorderWidth = "1px" Borderfont color = "Tan" Width = "499px" AutoGenerateColumns = "False" DataKeyField = "Email"> <SelectedItemStyle Forefont color = "GhostWhite" Backfont color = "DarkSlateBlue"> </SelectedItemStyle> <AlternatingItemStyl E Backfont color = "PaleGoldenrod"> </AlternatingItemStyle> <HeaderStyle Font-Bold = "True" Backfont color = "Tan"> </HeaderStyle> <FooterStyle Backfont color = "Tan"> </FooterStyle> <Columns> <asp: templateColumn SortExpression = "FirstName" HeaderText = "First Name"> <ItemTemplate> <asp: textBox id = First runat = "server" Width = "109px" Text = '<% # DataBinder. eval (Container, "DataItem. firstName ") %> '> </asp: TextBox> </ItemTemplate> <FooterTemplate> <asp: TextBox id = "NewFirst" runat = "server" Width = "109px"> </asp: TextBox> </FooterTemplate> </asp: templateColumn> <asp: TemplateColumn SortExpression = "LastName" HeaderText = "Last Name"> <ItemTemplate> <asp: textBox id = Last runat = "server" Width = "109px" Text = '<% # DataBinder. eval (Container, "DataItem. lastName ") %> '> </asp: TextBox> </ItemTemplate> <FooterTemplate> <asp: TextBo X id = "NewLast" runat = "server" Width = "109px"> </asp: TextBox> </FooterTemplate> </asp: TemplateColumn> <asp: templateColumn SortExpression = "Email" HeaderText = "Email"> <ItemTemplate> <asp: TextBox id = Email runat = "server" Text = '<% # DataBinder. eval (Container, "DataItem. email ") %> '> </asp: TextBox> </ItemTemplate> <FooterTemplate> <asp: TextBox id =" NewEmail "runat =" server "> </asp: textBox> </FooterTemplate> </ Sp: TemplateColumn> <asp: TemplateColumn HeaderText = "Delete Contact"> <ItemStyle HorizontalAlign = "Center"> </ItemStyle> <ItemTemplate> <asp: checkBox Runat = "server" ID = "chkDelete"> </asp: CheckBox> </ItemTemplate> <FooterStyle HorizontalAlign = "Center"> </FooterStyle> <FooterTemplate> <asp: linkButton Runat = "server" Text = "Add" CommandName = "Add" ID = "Linkbutton1" NAME = "Linkbutton1"> </asp: LinkButton> </Footer Template> </asp: TemplateColumn> </Columns> </asp: datagrid> ContactList. cs when I chose to use an XML file to access data, I decided to use DataSet to access it. Because DataSet objects have ReadXml and WriteXml methods, this is a very reasonable choice. The first step is to read data in XML. As you can see in the code, I have created a member to process data sorting. Private DataSet _ dsContacts; private string _ sSort; private void Page_Load (object sender, System. eventArgs e) {// load the XML file. _ dsContacts = new DataSet (); _ dsContacts. readXml (Server. mapPath ("Contacts. xml "); DataColumn [] dcPk = {_ dsContacts. tables ["Contact"]. columns ["Email"]}; _ dsContacts. tables ["Contact"]. primaryKey = dcPk; if (! Page. IsPostBack) {// if this is the first load, bind the data. BindContacts (); _ sSort = "FirstName";} else {// otherwise, read the sorting status from the view status. _ sSort = (string) ViewState ["Sort"] ;}} in step 2, I created a method to bind data to the grid, it contains the data sorting logic and the method for reading data from the disk. Private void BindContacts () {// Save the sorting status to the view status. viewState ["Sort"] = _ sSort; // bind the grid to the sorted data view. dataView dv = new DataView (_ dsContacts. tables ["Contact"]); dv. sort = _ sSort; dgContacts. dataSource = dv; dgContacts. dataBind ();} private void SaveContacts () {_ dsContacts. writeXml (Server. mapPath ("Contacts. xml ");} ItemCommand event is used to process adding new contacts to the list. Note: I checked whether the CommandName parameter is "Add". It is used to process the return value of the link button (LinkButton) IN THE FooterTemplate of the last column of the grid in the ASPX page. Private void dgContacts_ItemCommand (object source, System. web. UI. webControls. dataGridCommandEventArgs e) {// Add new data to dataset. here I use arrays to improve processing efficiency. if (e. commandName = "Add") {string [] sContact = {"", "", ""}; sContact [0] = (TextBox) e. item. findControl ("NewEmail ")). text; sContact [1] = (TextBox) e. item. findControl ("NewFirst ")). text; sContact [2] = (TextBox) e. item. findControl ("NewLast ")). text; _ dsContac Ts. tables ["Contact"]. rows. add (sContact); SaveContacts ();} BindContacts ();} I skipped the SortCommand code, because many other documents have discussed in detail how to sort. If you download the source code of this example, it will be included. Finally, I moved the Click Event (OnClick) of the link button on the form here. Here, we use the cyclic detection data items in the DataGrid to perform any necessary Delete and update operations. Private void btnUpdate_Click (object sender, System. eventArgs e) {// process each data item cyclically. foreach (maid di in dgContacts. items) {// you are sure that the data item is not the top or end of the page. if (di. itemType = ListItemType. item | di. itemType = ListItemType. alternatingItem) {// obtain the current row after the update or delete operation is executed. dataRow dr = _ dsContacts. tables ["Contact"]. rows. find (dgContacts. dataKeys [di. itemIndex]); // check whether a row needs to be deleted. if (CheckBox) di. findControl ("chkDelete ") ). Checked) {_ dsContacts. tables ["Contact"]. rows. remove (dr); // Delete specified row} else {// update data row. dr ["Email"] = (TextBox) di. findControl ("Email ")). text; dr ["FirstName"] = (TextBox) di. findControl ("First ")). text; dr ["LastName"] = (TextBox) di. findControl ("Last ")). text ;}}// save it if there is any change. if (_ dsContacts. hasChanges () {SaveContacts () ;}bindcontacts (); // bind}. In conclusion, I can easily find the Cells of each DataGridItem in the control through the control position ). There are multiple ways to implement it, and I'm sure you can find a better way to complete this task. As you can see, it is very easy to edit the entire data grid at a time. A slight modification to the same method can also be used for paging grid.

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.