
I'm looking for an example of how to insert a row, with data, into a radgrid. I've seen examples of how to trigger the insert command from Javascript. But I want more than just a new, empty row that the user can type into. I want to add a new, completed row, with data, to what is already bound to the grid, from Javascript.
Let's assume I have some JSON data (returned by an ajax call, for example) that I want to add as a new row into an existing radgrid on the page, all client side, Javascript based. I'm assuming that when the page is eventually posted back, I can then also iterate over all the rows (those orginally bound when the page was first rendered and any subsequent rows that were added by Javascript).
Any sample code or suggested links would be appreciated.
3 Answers, 1 is accepted
Hi Margo,
Please refer to the Client-Side Insert/Update/Delete demo showing similar functionality on how to insert a new row via client-side script. You may also check the following help topic:
Client-side Editing.
Here is an example:
<script type="text/javascript">
var dataSource = [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
];
function pageLoad() {
var masterTable = $find('<%=RadGrid1.ClientID%>').get_masterTableView();
masterTable.set_dataSource(dataSource);
masterTable.dataBind();
}
function addRecord() {
var masterTable = $find('<%=RadGrid1.ClientID%>').get_masterTableView();
var gridSource = masterTable.get_dataSource();
var data = [{ "firstName": "John", "lastName": "Smith" }];
var newSource = gridSource.concat(data);
masterTable.set_dataSource(newSource);
masterTable.dataBind();
}
</script>
<telerik:RadButton RenderMode="Lightweight" runat="server" AutoPostBack="false" Text="Insert Items" OnClientClicked="addRecord"></telerik:RadButton>
<telerik:RadGrid ID="RadGrid1" RenderMode="Lightweight" Width="97%" AllowPaging="True" PageSize="15" runat="server"
AllowSorting="true" GridLines="None">
<MasterTableView>
<Columns>
<telerik:GridBoundColumn UniqueName="firstName" DataField="firstName"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="lastName" DataField="lastName"></telerik:GridBoundColumn>
</Columns>
</MasterTableView>
<PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
<FilterMenu EnableTheming="True">
<CollapseAnimation Duration="200" Type="OutQuint"></CollapseAnimation>
</FilterMenu>
<ClientSettings>
<ClientEvents OnCommand="function(){}" />
</ClientSettings>
</telerik:RadGrid>
You can find additional details and ideas in the following resources:
- Client-side Binding Specifics
- Grid / Programmatic Binding
- RadGrid bound to RadClientDataSource demo
- Batch Editing demo
Alternatively, you can use the Kendo UI Grid which is entirely client-side based UI grid widged: https://demos.telerik.com/kendo-ui/grid/index.
Regards,
Rumen
Progress Telerik
Thank you for this! The bit of Javascript in the addRecord() function really helped clarify that for me.
A couple of more questions if I might...
So, I was able to add a couple of rows to my radgrid using that technique, but when I clicked a "Save" button and postedback to the page, I tried to loop through the grid items, but there wasn't any data. How do I get to the data that was added via Javascript on a postback (in the codebehind)?
My other question was the <ClientSettings> section. What does the ClientEvents / OnCommand=function(){} do, actually? I'm not following what that sets up...
Thanks in advance.
foreach (GridDataItem gridDataItem in gridMain.Items) { // nothing here }
Hi,
To address your questions:
Accessing Client-Side Added Data in Code-Behind
When you add data to the RadGrid on the client side using JavaScript, these changes are not automatically sent to the server on postback. To access this data in the code-behind, you need to ensure that the client-side changes are communicated back to the server. Here are some approaches to achieve this:
Hidden Field Approach: Store the client-side changes in a hidden field, then access this hidden field in the code-behind during postback. This method involves converting your client-side data into a JSON string and storing it in a hidden field.
function addRecord() { var masterTable = $find('<%=RadGrid1.ClientID%>').get_masterTableView(); var gridSource = masterTable.get_dataSource(); var data = [{ "firstName": "John", "lastName": "Doe" }]; var newSource = gridSource.concat(data); masterTable.set_dataSource(newSource); masterTable.dataBind(); // Store the updated data source in a hidden field document.getElementById('<%= hiddenField.ClientID %>').value = JSON.stringify(newSource); }
In the code-behind, you can parse this JSON to retrieve the data:
string jsonData = hiddenField.Value; var data = JsonConvert.DeserializeObject<List<YourDataType>>(jsonData);
AJAX Web Service: Use an AJAX call to send the client-side data to the server. This allows you to process and store the data as needed without relying on a page postback. Check this forum post: https://www.telerik.com/forums/add-new-row-onclient-javascript#1643764 and try the attached sample project.
Understanding ClientEvents / OnCommand
The <ClientSettings> section in the RadGrid configuration is used to define client-side behaviors and events. The OnCommand event is a client-side event that can execute JavaScript code when a command is fired from the grid, such as sorting, paging, or custom commands.
Functionality: It allows you to handle grid commands on the client-side before they are sent to the server. This can be useful for implementing custom logic, validation, or modifying the command before it is processed.
function onCommand(sender, args) { var commandName = args.get_commandName(); if (commandName === "CustomCommand") { // Custom logic here alert("Custom command executed!"); } }
To set this up, define the event in your ASPX markup:
<ClientSettings> <ClientEvents OnCommand="onCommand" /> </ClientSettings>
Comparison of Approaches
Hidden Field: This is straightforward and works well if you want to handle data on postback. It's ideal when dealing with small datasets.
AJAX Web Service: Useful for more dynamic applications where you want to handle data without reloading the page. This is more scalable for larger datasets or frequent updates.
If you need further details or examples, feel free to ask!
Please refer to the following forum for additional information:
Regards,
Rumen
Progress Telerik
Again, thank you! I can work with stashing the json-based datasource in a hidden field or otherwise posting it via ajax.
I also want to be able to delete a row, client side. To that end, I've added an OnCommand="gridCommand" setting. and created an "gridCommand()" Javascript function. I've also added a GridButton to my grid. What I'm trying to figure out is when that button is clicked, how to get the index of (or any reference to) the row that button was clicked in.
In the grid markup, I've added:
<telerik:GridButtonColumn CommandName="Delete" Text ="Delete" ItemStyle-HorizontalAlign="Center"</telerik:GridButtonColumn>
<ClientSettings>
<ClientEvents OnCommand="gridCommand" />
</ClientSettings>
and a stub for my Javascript function:
function gridCommand(sender, args) { console.log("gridCommand"); // how to get current row? args.set_cancel(true); }
Can I get the current row? I would need to get the "clientDataKey" or some other value from the current row that I can use to match it in the json/client side datasource and remove it from that datasource...
Hi Margo
To get the index or reference to the row where the button was clicked, you can use the args parameter in your gridCommand JavaScript function. Here's how you can achieve this:
Step-by-Step Guide
Access the Grid Data Item: You can access the grid data item from the args parameter using the get_item() method. This will give you the row where the command was triggered.
Retrieve the Data Key: If you have set a ClientDataKeyNames property in your grid, you can retrieve the value using the args.getDataKeyValue method.
Here's an updated version of your gridCommand function:
function gridCommand(sender, args) {
// Check if the command name is "Delete"
if (args.get_commandName() === "Delete") {
// Get the grid data item
var item = args.get_item();
// Retrieve the data key value (assuming "ID" is your data key)
var dataKeyValue = item.getDataKeyValue("ID");
console.log("Deleting row with ID: " + dataKeyValue);
// Cancel the default delete behavior if needed
args.set_cancel(true);
// Here you can remove the item from your JSON data source
removeFromDataSource(dataKeyValue);
}
}
// Example function to remove an item from your JSON data source
function removeFromDataSource(dataKeyValue) {
// Assuming `dataSource` is your JSON data array
dataSource = dataSource.filter(function(item) {
return item.ID !== dataKeyValue;
});
// Rebind the grid with the updated data source
var masterTable = $find('<%=RadGrid1.ClientID%>').get_masterTableView();
masterTable.set_dataSource(dataSource);
masterTable.dataBind();
}
You can also try the approach shown in this forum reply: https://www.telerik.com/forums/custom-delete-confirmation-with-parameters#1401564.
Additional Notes
ClientDataKeyNames: Ensure that you have set the
ClientDataKeyNames
property on yourMasterTableView
to the appropriate field that uniquely identifies each row, such as an "ID". If you haven't set this property, please confirm what field you intend to use as the unique identifier.Data Source Management: The
removeFromDataSource
function should match the logic you use to manage your client-side data source. Adjust it according to your data structure.
This approach will help you handle the deletion of a row on the client side effectively, updating your JSON data source accordingly. If you need further assistance, feel free to ask!
Regards,
Rumen
Progress Telerik