Accessing and Controlling FormTemplate Buttons in RadGrid Based on CommandName
Environment
Product | RadGrid for ASP.NET AJAX |
Version | All |
Description
In a scenario where a RadGrid utilizes CommandItemTemplate buttons alongside a FormTemplate for inserting or updating records, it's necessary to show specific buttons based on the action the user intends to perform (e.g., Insert or Update). This article demonstrates accessing buttons within a FormTemplate based on the CommandName, such as "InitInsert" for initiating an insert action.
This KB article also answers the following questions:
- How do I make the Insert or Update button visible in RadGrid FormTemplate based on the command issued?
- What is the method to access controls within a FormTemplate in RadGrid?
- Can I dynamically show or hide buttons in a RadGrid FormTemplate?
Solution
To access and manipulate the visibility of Insert or Update buttons within a FormTemplate based on the CommandName
, use the FindControl
method to locate these buttons. Below is a step-by-step guide implemented in VB.NET:
- Handle the
ItemCommand
event of the RadGrid. - Check if the event is triggered by an item in edit mode.
- Use the
FindControl
method to locate the Insert and Update buttons within the FormTemplate. - Adjust the visibility of these buttons based on the
CommandName
.
Here is a code snippet that illustrates the process:
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem item = (GridEditableItem)e.Item;
RadButton insertButton = (RadButton)item.FindControl("InsertButton");
RadButton updateButton = (RadButton)item.FindControl("EditButton");
if (e.CommandName == "PerformInsert")
{
if (insertButton != null)
insertButton.Visible = true;
if (updateButton != null)
updateButton.Visible = false;
}
else if (e.CommandName == "Edit")
{
if (insertButton != null)
insertButton.Visible = false;
if (updateButton != null)
updateButton.Visible = true;
}
}
System.Environment.Exit(0); /* TODO ERROR: Skipped SkippedTokensTrivia */
}
Replace "InsertButton"
and "EditButton"
with the actual IDs of your Insert and Update buttons within the FormTemplate. This example makes the Insert button visible and the Update button hidden when the PerformInsert
command is triggered, and vice versa for the Edit
command.