The code for this tutorial can be downloaded from here:
The first thing a developer wants to do with data is to
manipulate it: create, read, update and delete it from a source repository
following client requirements. ASP.NET 2.0 has added a control in order to do
that with tabular data showing it in a grid. The control is called
“GridView” and replaces the old “DataGrid” from
previous versions. But if we combine its use with an ObjectDataSource or any
other ASP.NET data source objects the codification of the common behavior in a
grid (CRUD operations, paging, sorting) are done more easily in a declarative
way not in a programmatic way.
Steps
1. First
of all create a web application with Visual Studio and call it “GridViewEditing”:
2. The
first step is to add a “GridView” to an empty page. Drag and drop
the control into the page.
3. Then
let’s use a DataSource for the “GridView”, it can be any data
source available at the tool box of Visual Studio, for our sample the
ObjectDataSource will be used. Drag and drop the control into the page
don’t specify any setting for this data source. The Visual Studio
“GridView” designer allows the use of a DataSource for this
“GridView”. Select the created object data source from the previous
step.
4. The
data base structure will be the class Entity and the store for this data
structure instances will be for this example the ASP.NET Session. Create the following
class into the App_Code folder, use a namespace for example: GridViewEditing
namespace GridViewEditing
{
public class Entity
{
public Guid Id { get; set;
}
public string Field1 { get; set;
}
public int Field2 { get; set;
}
public DateTime Field3 { get; set;
}
public bool Field4 { get; set;
}
public bool Selected { get; set;
}
}
}
5. Now
the object data source needs a class (Business Object) that will provide the
methods for doing the data access operations, create a class for that:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Web;
namespace GridViewEditing
{
public class DAOEntity
{
public IList<Entity> GetAll()
{
IList<Entity> entities = GetFromSession();
return entities;
}
public void Update(Entity entity)
{
IList<Entity> entities = GetFromSession();
Entity found = (from e in entities
where e.Id == entity.Id
select e).SingleOrDefault<Entity>();
if (found != null)
{
found.Field1 = entity.Field1;
found.Field2 = entity.Field2;
found.Field3 = entity.Field3;
found.Field4 =
entity.Field4;
}
}
public void Insert(Entity entity)
{
IList<Entity> entities = GetFromSession();
entities.Add(entity);
}
public void Delete(Entity entity)
{
IList<Entity> entities = GetFromSession();
if (!entities.Remove(entity))
{
Entity found = (from e in entities
where e.Id == entity.Id
select e).SingleOrDefault<Entity>();
entities.Remove(found);
}
}
private Random random = new Random();
private IList<Entity> GetFromSession()
{
IList<Entity> entities = HttpContext.Current.Session["Entities"] as IList<Entity>;
if (entities == null)
{
entities = CreateNewList();
HttpContext.Current.Session["Entities"] = entities;
}
return entities;
}
private IList<Entity> CreateNewList()
{
IList<Entity> entities = new List<Entity>();
entities.Add(CreateNewEntity());
entities.Add(CreateNewEntity());
entities.Add(CreateNewEntity());
entities.Add(CreateNewEntity());
entities.Add(CreateNewEntity());
entities.Add(CreateNewEntity());
entities.Add(CreateNewEntity());
entities[0].Selected = true;
return entities;
}
private Entity CreateNewEntity()
{
Entity entity = new Entity();
entity.Id = Guid.NewGuid();
entity.Field1 = entity.Id.ToString();
entity.Field2 = random.Next(1, 1000000);
entity.Field3 = new DateTime(random.Next(1900, 2010), random.Next(1,
12), random.Next(1, 29));
entity.Field4 = entity.Field2 % 2 == 0;
entity.Selected = false;
return entity;
}
}
}
6. Modify
the object data source settings using the new created class:
7. Enable
Sorting, Pagination, Edition, Deletion, Selection to the GridView:
8. Add
columns to the GridView use template fields, for each 5 fields:
There is a CommandField that has been
created by enabling Editing, Deleting and Selection. This field creates link
buttons for those operations.
9. Compile
and run the page.
10. Customize
the template fields:
After using the link “Edit
Templates” you can see the templates and select any of them, a column has
many templates the most interesting for this tutorial are ItemTemplate and
EditItemTemplate. For example here is a hidden field that will store the data
row id.
11. Usually
the ItemTemplate has a label for showing data and EditItemTemplate can have any
control that helps the user to input data easily:
a. For example the Field1 is a string and a we can
use a TextBox for editing in many lines:
b. Here is a TextBox with a Date as input and with
an ajax extender and a date validator.
c. Here a Checkbox for a Boolean.
Important: For showing data (ItemTemplate)
the “Custom binding: Code expression: ” must be
Eval(“TheBoundFieldName”) but for editing data (EditDataTemplate)
it must be Bind(“TheBoundFieldName”)
and it is possible to add some format i.e. :
Eval(“Field4”,”{0:d}”) and Bind(“Field4”).
It is possible to bind any control property
to a field.
Note.- For this tutorial the data source was an Object
Datasource and an IList was used which not allowed to use the sorting option,
if using other data sources that uses DataTable or DataSet sorting is automatic
with GridView. Sorting can be added using Object Datasource to GridView by
modifying the header template and adding event handlers to the grid databind
event but that’s another tutorial.
Generate ASP.NET code
Finally after adding some styles to format to the grid the
generated ASP.NET code could be:
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" AutoGenerateColumns="False"
AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5"
DataKeyNames="Id">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:TemplateField HeaderText="Id" SortExpression="Id" ControlStyle-Width="0px" ShowHeader="False">
<EditItemTemplate>
<asp:HiddenField ID="hiddenId" runat="server" Value='<%#
Bind("Id") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:HiddenField ID="hiddenId" runat="server" Value='<%#
Bind("Id") %>' />
</ItemTemplate>
<ControlStyle Width="0px"></ControlStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Field1" SortExpression="Field1" ItemStyle-Width="400px">
<EditItemTemplate>
<asp:TextBox ID="textBoxField1" runat="server" Text='<%#
Bind("Field1") %>' ToolTip="A text"
TextMode="MultiLine" MaxLength="200" Width="90%"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#
Eval("Field1") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="400px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Field2" SortExpression="Field2">
<EditItemTemplate>
<asp:TextBox ID="textBoxField2" runat="server" Text='<%#
Bind("Field2") %>'></asp:TextBox>
<cc1:MaskedEditExtender ID="textBoxField2_MaskedEditExtender" runat="server" CultureAMPMPlaceholder=""
CultureCurrencySymbolPlaceholder="" CultureDateFormat="" CultureDatePlaceholder=""
CultureDecimalPlaceholder="" CultureThousandsPlaceholder="" CultureTimePlaceholder=""
Enabled="True" Mask="9999999" MaskType="Number" TargetControlID="textBoxField2">
</cc1:MaskedEditExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#
Eval("Field2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Field3" SortExpression="Field3">
<EditItemTemplate>
<asp:TextBox ID="textBoxCreatedDate" runat="server" Text='<%#
Bind("Field3") %>'></asp:TextBox>
<asp:ImageButton AlternateText="Schedule" ID="imageButtonCreatedDate" runat="server"
ImageUrl="~/images/Calendar_scheduleHS.png" CausesValidation="False" /><cc1:MaskedEditExtender
runat="server" TargetControlID="textBoxCreatedDate" Mask="99/99/9999" MessageValidatorTip="true"
OnFocusCssClass="MaskedEditFocus" OnInvalidCssClass="MaskedEditError" MaskType="Date"
InputDirection="RightToLeft" ErrorTooltipEnabled="True" ID="maskedEditExtenderCreatedDate" />
<cc1:MaskedEditValidator ID="maskedEditValidatorCreatedDate" runat="server" ControlExtender="maskedEditExtenderCreatedDate"
ControlToValidate="textBoxCreatedDate" IsValidEmpty="False" EmptyValueMessage="*
Created Date is required"
InvalidValueMessage="Created Date is invalid" MaximumValueMessage="" EmptyValueBlurredText="*
Required"
InvalidValueBlurredMessage="* Required" MaximumValueBlurredMessage="*" MinimumValueBlurredText="*"
Display="Dynamic" TooltipMessage="mm/dd/yyyy" MinimumValue="01/01/1753" MinimumValueMessage="Created
Date cannot be less than 01/01/1753"
CssClass="validator" /><cc1:CalendarExtender ID="calendarExtenderCreatedDate" runat="server"
TargetControlID="textBoxCreatedDate" PopupButtonID="imageButtonCreatedDate" Format="MM/dd/yyyy"
Animated="False">
</cc1:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="labelField3" runat="server" Text='<%#
Eval("Field3", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Field4" SortExpression="Field4">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#
Bind("Field4") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#
Eval("Field4") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
How to obtain changes
If the “Bind” method is used inside
EditItemTemplate and a DataSource is used then the changes are automatically
done by the selected data source, but if the grid don’t use a data source
control and uses:
DAOEntity dao = new DAOEntity();
gridViewId.DataSource = dao.GetAll();
gridViewId.DataBind();
It will be needed to use the following code for obtaining
changes from the template controls.
DAOEntity dao = new DAOEntity();
IList<Entity> entities = dao.GetAll();
foreach (GridViewRow row in gridViewId.Rows)
{
HiddenField hiddenId = row.FindControl("HiddenId") as HiddenField;
int id = Convert.ToInt32(hiddenId.Value);
TextBox textBox = row.FindControl("TextBox1") as TextBox;
if (textBox != null)
{
//update the data with textBox.Text
entities[id].Field1 = textBox.Text;
}
}
//Save changes from entities collection
Related Tutorial from Microsoft can be found here:
http://msdn.microsoft.com/en-us/library/bb288032.aspx
Comentarios
Publicar un comentario