by Al Beecy
January 7, 2009
Most of the examples floating around that show how to do inline- or FormTemplate-based editing with Telerik's RadGrid use the SqlDataSource's InsertCommand, UpdateCommand, and DeleteCommand properties along with a bunch of declarative parameters to manipulate the data. Since I don't believe that ASPX pages are an appropriate place to be sprinkling SQL around, I put together this brief example of how to use a FormTemplate for editing, but keep the data-tweaking in code-behind where it belongs.
To do this, the following steps are needed:
1. In the RadGrid tag, declare a handler for the OnUpdateCommand event.
OnUpdateCommand="RadGrid1_UpdateCommand"
2. Be sure your MasterTableView's DataKeyNames property is set to the primary key of the table.
DataKeyNames="CategoryID"
3. Add a GridEditCommandColumn to the grid's columns collection.
<telerik:GridEditCommandColumn ButtonType="ImageButton"
UniqueName="EditCommandColumn" />
4. Declare an EditFormSettings section and make sure you set its EditFormType to "Template" or you will get the baked in auto-form. Inside of the FormTemplate tag, put whatever you need in terms of a editing form.
<EditFormSettings EditFormType="Template">
<EditColumn UniqueName="EditColumn"></EditColumn>
<FormTemplate>
<table border="0" cellpadding="2">
<tr>
<td>Category Name: </td>
<td>
<asp:TextBox ID="txtCategoryName" Width="250px"
Text='<%# Bind( "CategoryName") %>'
runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Description: </td>
<td>
<asp:TextBox ID="txtDescription" Width="250px"
Text='<%# Bind( "Description") %>' TextMode="MultiLine"
Rows="4" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<asp:Button ID="btnUpdate" CommandName="Update"
Text="Update" runat="server" />
<asp:Button ID="btnCancel" CommandName="Cancel"
Text="Cancel" runat="server" />
</FormTemplate>
</EditFormSettings>
5. Add the event handler to the code-behind. In this case, I'm using LLBLGen to update the data.
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.UpdateCommandName)
{
if (e.Item is GridEditFormItem)
{
GridEditFormItem item = (GridEditFormItem)e.Item;
int id = Convert.ToInt32(item.GetDataKeyValue("CategoryID"));
if (id != 0)
{
TextBox txtCategoryName =
(TextBox)item.FindControl("txtCategoryName");
TextBox txtDescription =
(TextBox)item.FindControl("txtDescription");
CategoriesEntity c = new CategoriesEntity(id);
c.CategoryName = txtCategoryName.Text;
c.Description = txtDescription.Text;
c.Save();
RadGrid1.Rebind();
}
}
}
}
This example can be easily extended to handle inserts and deletes.
Applies to: RadGrid for ASP.NET AJAX Version Q3 2008