Create a fully editable DataGrid ··············

Source: Internet
Author: User

Check boxes, text boxes, and so on in each row of the DataGrid? How to update their values? The answer is quite simple.Article, I will show you how to complete it.

We all know that DataGrid is a very powerful tool. Based on my experience, in more than 90% of the time,DataGridAre used to display data, and a row of data may be edited at a time. In some cases, you may need to edit multiple rows or even all data at a time. An actual example is the application of selling items online.Program, The 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.

Concept

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 preferCode.

Contacts. xml

The XML data file in this example 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>
<Contact>
<Email> youraddress@yourcompany.com </Email>
<Firstname> Jane </firstname>
<Lastname> Doe </lastname>
</Contact>
</Contacts>

Contactlist. aspx

Setting webform is very simple. I placed a newDataGridTo 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 to the Data Template (Itemtemplate). This is a technique for displaying anything other than text in each line of the grid. In addition, you will also notice thatFootertemplateTo 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 = "lightgoldenrodyellow" borderwidth = "1px" borderfont color = "Tan" width = "499px" autogeneratecolumns = "false" datakeyfield = "email">
<Selecteditemstyle forefont color = "ghostwhite" backfont color = "darkslateblue"> </selecteditemstyle>
<Alternatingitemstyle backfont color = "palegoldenrod"> </alternatingitemstyle>
<Headerstyle font-bold = "true" backfont color = "Tan"> <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: textbox 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>
</ASP: 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>
</Footertemplate>
</ASP: templatecolumn>
</Columns>
</ASP: DataGrid>

Contactlist. CS

When I chose to use an XML file to access the data, I decided to use dataset to access it. BecauseDatasetObject hasReadxmlAndWritexmlMethod, so 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"];
}
}

Step 2: I created a method to bind data to the grid. It contains the data sorting logic and the method to read data from the disk.

private void bindcontacts ()
{< br> // 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 ();
}< br>
private void savecontacts ()
{< br> _ dscontacts. writexml (server. mappath ( "contacts. XML " );
}

ItemcommandEvents are used to add new contacts to the list. Note: I checkedCommandnameWhether the parameter isAddIt is used to process the footer template of the last column of the grid in the ASPX page (In footertemplate)The Return Value of the link button.

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;

_ Dscontacts. Tables ["Contact"]. Rows. Add (scontact );

Savecontacts ();
}

Bindcontacts ();
}

I skippedSortcommandCode, because many other documents have discussed in detail how to sort the code. If you downloadSource code.

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)
{
// Make 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); // deletes a specified row.
}
Else
{
// Update the 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 it changes.
If(_ Dscontacts. haschanges ())
{
Savecontacts ();
}

Bindcontacts (); // bind
}

Conclusion

I can easily find the cells of every datagriditem in the control through the control's 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.