In the example shown for batch update in the below link, I used NeedDataSource event handler to bind the data to the grid and ItemDataBound to bind the DropDownLists. But I dont see the DropDownList getting populated may be due to the dropdownlist's style property Style="display: none". And the function HideEditor never gets executed becuase the variable 'colName' is null. Do I have to use SqlDataSource only to get this working?
http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/clienteditbatchupdates/defaultvb.aspx
Appreciate your help!!
Neelima
function UpdateValues(grid) { //determine the name of the column to which the edited cell belongs var tHeadElement = grid.get_element().getElementsByTagName("thead")[0]; var headerRow = tHeadElement.getElementsByTagName("tr")[0]; var colName = grid.get_masterTableView().getColumnUniqueNameByCellIndex(headerRow, editedCell.cellIndex); //based on the column name, extract the value from the editor, update the text of the label and switch its visibility with that of the column //column. The update happens only when the column editor value is different than the non-editable value. We also set dashed border to indicate //that the value in the cell is changed. The logic is isolated in the HideEditor js method switch (colName) { case "Start_Dt": HideEditor(editedCell, "textbox"); break; case "PickupAddr1": HideEditor(editedCell, "textbox"); break; case "TypeOfFare": HideEditor(editedCell, "textbox"); break; default: break; } }function HideEditor(editCell, editorType) { //get reference to the label in the edited cell var lbl = editCell.getElementsByTagName("span")[0]; switch (editorType) { case "textbox": var txtBox = editCell.getElementsByTagName("input")[0]; if (lbl.innerHTML != txtBox.value) { lbl.innerHTML = txtBox.value; editCell.style.border = "1px dashed"; StoreEditedItemId(editCell); } txtBox.style.display = "none"; break; case "checkbox": var chkBox = editCell.getElementsByTagName("input")[0]; if (lbl.innerHTML.toLowerCase() != chkBox.checked.toString()) { lbl.innerHTML = chkBox.checked; editedCell.style.border = "1px dashed"; StoreEditedItemId(editCell); } chkBox.style.display = "none"; editCell.getElementsByTagName("span")[1].style.display = "none"; break; case "dropdown": var ddl = editCell.getElementsByTagName("select")[0]; var selectedValue = ddl.options[ddl.selectedIndex].value; if (lbl.innerHTML != selectedValue) { lbl.innerHTML = selectedValue; editCell.style.border = "1px dashed"; StoreEditedItemId(editCell); } //if the form decorator was enabled, hide the decorated dropdown instead of the original. if (ddl.className == "rfdRealInput") ddl = Telerik.Web.UI.RadFormDecorator.getDecoratedElement(ddl); ddl.style.display = "none"; default: break; } lbl.style.display = "inline"; }6 Answers, 1 is accepted
Could you share the code-behind with us? I suppose that dropdownlist is not populated because it is not bounded properly. Try to set debugger in the ItemDataBound and make sure that items are correctly populated win the DropDownList.
Greetings,
Vasil
the Telerik team
I am getting the same exact problem when I try to test the same sample using the VS2012 and Telerik2012. Can somebody post the solution for that. code behind is as follows, aspx is exact same as in sample but i am not using SQLDataSource. I do not have any dropdowns . I have only labels and textboxes.
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using Telerik.Web.UI;using BFNReportProject.DataClasses;using BFNReportProject.CommonClasses;using BFNReportProject.Controls;using BFNReportProject.BFNRTR.RTRClasses;namespace BFNReportProject.Controls{ public partial class Blanket : System.Web.UI.UserControl { private DataTable dt; protected void Page_Load(object sender, EventArgs e) { } private DataTable BindBlanketData() { dt = RTRClass.GetBlanketTable("5", "21", "ZE", "1543", "OR1"); if (dt.Rows.Count == 0) { //lblerror.Visible = true; // lblerror.Text = "No Data Found"; } Session["BlanketTable"] = dt; return dt; } protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e) { RadGrid1.DataSource = BindBlanketData(); } private void SetMessage(string message) { Label1.Text = string.Format("<span>{0}</span>", message); } protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e) { /* if (e.Item is GridDataItem) { GridDataItem dataItem = (GridDataItem)e.Item; TextBox txtBox = (TextBox)dataItem.FindControl("txtBoxName"); TextBoxSetting stringSetting = (TextBoxSetting)RadInputManager1.GetSettingByBehaviorID("StringBehavior"); stringSetting.TargetControls.Add(new TargetInput(txtBox.UniqueID, true)); txtBox = (TextBox)dataItem.FindControl("txtQuantityPerUnit"); stringSetting.TargetControls.Add(new TargetInput(txtBox.UniqueID, true)); txtBox = (TextBox)dataItem.FindControl("txtUnitPrice"); NumericTextBoxSetting currencySetting = (NumericTextBoxSetting)RadInputManager1.GetSettingByBehaviorID("CurrencyBehavior"); currencySetting.TargetControls.Add(new TargetInput(txtBox.UniqueID, true)); txtBox = (TextBox)dataItem.FindControl("txtUnitsOnOrder"); NumericTextBoxSetting numericSetting = (NumericTextBoxSetting)RadInputManager1.GetSettingByBehaviorID("NumberBehavior"); numericSetting.TargetControls.Add(new TargetInput(txtBox.UniqueID, true)); }*/ } protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e) { if (e.Argument == string.Empty) { RadGrid1.Rebind(); } string[] editedItemIds = e.Argument.Split(':'); int i; for (i = 0; i <= editedItemIds.Length - 2; i++) { string productId = editedItemIds[i]; GridDataItem updatedItem = RadGrid1.MasterTableView.FindItemByKeyValue("ProductID", int.Parse(productId)); UpdateValues(updatedItem); } } protected void UpdateValues(GridDataItem updatedItem) { TextBox txtBox = (TextBox)updatedItem.FindControl("txtPkgQty"); // SqlDataSource1.UpdateParameters["ProductName"].DefaultValue = txtBox.Text; txtBox = (TextBox)updatedItem.FindControl("txtQtyAvail"); // SqlDataSource1.UpdateParameters["QuantityPerUnit"].DefaultValue = txtBox.Text; // txtBox = (TextBox)updatedItem.FindControl("txtUnitPrice"); // SqlDataSource1.UpdateParameters["UnitPrice"].DefaultValue = txtBox.Text; //txtBox = (TextBox)updatedItem.FindControl("txtUnitsOnOrder"); // SqlDataSource1.UpdateParameters["UnitsOnOrder"].DefaultValue = txtBox.Text; // DropDownList ddl = (DropDownList)updatedItem.FindControl("ddlUnitsInStock"); // SqlDataSource1.UpdateParameters["UnitsInStock"].DefaultValue = ddl.SelectedValue; // CheckBox chkBox = (CheckBox)updatedItem.FindControl("chkBoxDiscontinued"); // SqlDataSource1.UpdateParameters["Discontinued"].DefaultValue = chkBox.Checked.ToString(); // SqlDataSource1.UpdateParameters["ProductID"].DefaultValue = updatedItem.GetDataKeyValue("ProductID").ToString(); try { // SqlDataSource1.Update(); } catch (Exception ex) { SetMessage(Server.HtmlEncode("Unable to update Products. Reason: " + ex.StackTrace).Replace("'", "'").Replace("\r\n", "<br />")); } SetMessage("Product with ID: " + updatedItem.GetDataKeyValue("Customer_Store_Id") + " updated"); } }}colName is null when I am expecting the exact column name to be assigned..
function UpdateValues(grid) { alert("UpdateValues"); //determine the name of the column to which the edited cell belongs var tHeadElement = grid.get_element().getElementsByTagName("thead")[0]; alert(tHeadElement); var headerRow = tHeadElement.getElementsByTagName("tr")[0]; alert(headerRow); var colName = grid.get_masterTableView().getColumnUniqueNameByCellIndex(headerRow, editedCell.cellIndex); alert(colName);
I am unable to see in your code where you set editedCell. See the source of the demo where the editedCell is set. http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/clienteditbatchupdates/defaultvb.aspx
Confirm that in your code the index is correct and not null. If the index is incorrect the getColumnUniqueNameByCellIndex will not find the correct ColumnUniqueName.
All the best,
Vasil
the Telerik team
var colName = grid.get_masterTableView().getColumnUniqueNameByCellIndex(headerRow, editedCell.cellIndex);
var masterTable = $find("<%=RadGrid1.ClientID%>").get_masterTableView();
var name = masterTable.getColumnUniqueNameByCellIndex(masterTable.HeaderRow, editedCell.cellIndex);
which worked but when I try to Add AddNewRecord into the same usercontrol, I am unable to see the AddNewRecord on the page, the entire functionality is not working. the code is as follows:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Blanket.ascx.cs" Inherits="BFNReportProject.Controls.Blanket" %><telerik:RadScriptManager runat="server" ID="RadScriptManager1" /><telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"> <script type="text/javascript"> var editedCell; var arrayIndex = 0; var editedItemsIds = []; function RowCreated(sender, eventArgs) { var dataItem = eventArgs.get_gridDataItem(); //traverse the cells in the created client row object and attach dblclick handler for each of them for (var i = 1; i < dataItem.get_element().cells.length; i++) { var cell = dataItem.get_element().cells[i]; if (cell) { $addHandler(cell, "dblclick", Function.createDelegate(cell, ShowColumnEditor)); } } } //detach the ondblclick handlers from the cells on row disposing function RowDestroying(sender, eventArgs) { if (eventArgs.get_id() === "") return; var row = eventArgs.get_gridDataItem().get_element(); var cells = row.cells; for (var j = 0, len = cells.length; j < len; j++) { var cell = cells[j]; if (cell) { $clearHandlers(cell); } } } function RowClick(sender, eventArgs) { if (editedCell) { //if the click target is table cell or span and there is an edited cell, update the value in it //skip update if clicking a span that happens to be a form decorator element (having a class that starts with "rfd") if ((eventArgs.get_domEvent().target.tagName == "TD") || (eventArgs.get_domEvent().target.tagName == "SPAN" && !eventArgs.get_domEvent().target.className.startsWith("rfd"))) { UpdateValues(sender); editedCell = false; } } } function UpdateValues(grid) { //determine the name of the column to which the edited cell belongs var tHeadElement = grid.get_element().getElementsByTagName("thead")[0]; var headerRow = tHeadElement.getElementsByTagName("tr")[0]; var colName = grid.get_masterTableView().getColumnUniqueNameByCellIndex(headerRow, editedCell.cellIndex); var masterTable = $find("<%=RadGrid1.ClientID%>").get_masterTableView(); var name = masterTable.getColumnUniqueNameByCellIndex(masterTable.HeaderRow, editedCell.cellIndex); //based on the column name, extract the value from the editor, update the text of the label and switch its visibility with that of the column //column. The update happens only when the column editor value is different than the non-editable value. We also set dashed border to indicate //that the value in the cell is changed. The logic is isolated in the HideEditor js method switch (name) { case "pkgQty": HideEditor(editedCell, "textbox"); break; case "QtyAvail": HideEditor(editedCell, "textbox"); break; default: break; } } function ShowColumnEditor() { editedCell = this; if (this.getElementsByTagName("span")[0]) { //hide text and show column editor in the edited cell var cellText = this.getElementsByTagName("span")[0]; cellText.style.display = "none"; } //display the span which wrapps the hidden checkbox editor if (this.getElementsByTagName("span")[1]) { this.getElementsByTagName("span")[1].style.display = ""; } var colEditor = this.getElementsByTagName("input")[0] || this.getElementsByTagName("select")[0]; //if the column editor is a form decorated select dropdown, show it instead of the original if (colEditor) { if (colEditor.className == "rfdRealInput" && colEditor.tagName.toLowerCase() == "select") colEditor = Telerik.Web.UI.RadFormDecorator.getDecoratedElement(colEditor); colEditor.style.display = ""; colEditor.focus(); } } function StoreEditedItemId(editCell) { //get edited row key value and add it to the array which holds them var gridRow = $find(editCell.parentNode.id); // var rowKeyValue = gridRow.getDataKeyValue("Customer_id,Customer_Store_Id,customer_item_sku"); var rowKeyValue = gridRow.getDataKeyValue("row_id"); Array.add(editedItemsIds, rowKeyValue); } function HideEditor(editCell, editorType) { //get reference to the label in the edited cell var lbl = editCell.getElementsByTagName("span")[0]; alert("lbl is :" + lbl.innerHTML); switch (editorType) { case "textbox": var txtBox = editCell.getElementsByTagName("input")[0]; alert("txtBox is :" + txtBox.value); if (lbl.innerHTML != txtBox.value) { lbl.innerHTML = txtBox.value; editedCell.style.border = "2px dashed"; StoreEditedItemId(editCell); } txtBox.style.display = "none"; break; case "checkbox": var chkBox = editCell.getElementsByTagName("input")[0]; if (lbl.innerHTML.toLowerCase() != chkBox.checked.toString()) { lbl.innerHTML = chkBox.checked; editedCell.style.border = "1px dashed"; StoreEditedItemId(editCell); } chkBox.style.display = "none"; editCell.getElementsByTagName("span")[1].style.display = "none"; break; case "dropdown": var ddl = editCell.getElementsByTagName("select")[0]; var selectedValue = ddl.options[ddl.selectedIndex].value; if (lbl.innerHTML != selectedValue) { lbl.innerHTML = selectedValue; editCell.style.border = "1px dashed"; StoreEditedItemId(editCell); } //if the form decorator was enabled, hide the decorated dropdown instead of the original. if (ddl.className == "rfdRealInput") ddl = Telerik.Web.UI.RadFormDecorator.getDecoratedElement(ddl); ddl.style.display = "none"; default: break; } lbl.style.display = "inline"; } function CancelChanges() { alert("CancelChanges"); if (editedItemsIds.length > 0) { $find("<%=RadAjaxManager1.ClientID %>").ajaxRequest(""); } else { alert("No pending changes to be discarded"); } editedItemsIds = []; } function ProcessChanges() { alert("Process Changes" + editedItemsIds.length); //extract edited rows ids and pass them as argument in the ajaxRequest method of the manager if (editedItemsIds.length > 0) { var Ids = ""; for (var i = 0; i < editedItemsIds.length; i++) { Ids = Ids + editedItemsIds[i] + ":"; } $find("<%=RadAjaxManager1.ClientID %>").ajaxRequest(Ids); } else { alert("No pending changes to be processed"); } editedItemsIds = []; } function RadGrid1_Command(sender, eventArgs) { //Note that this code has to be executed if you postback from external control instead from the grid (intercepting its onclientclick handler for this purpose), //otherwise the edited values will be lost or not propagated in the source if (editedItemsIds.length > 0) { if (eventArgs.get_commandName() == "Sort" || eventArgs.get_commandName() == "Page" || eventArgs.get_commandName() == "Filter") { if (confirm("Any unsaved edited values will be lost. Choose 'OK' to discard the changes before proceeding or 'Cancel' to abort the action and process them.")) { editedItemsIds = []; } else { //cancel the chosen action eventArgs.set_cancel(true); //process the changes ProcessChanges(); editedItemsIds = []; } } } } document.forms[0].onsubmit = function () { var hasDeletedItems = $find("<%= RadGrid1.ClientID %>")._deletedItems.length > 0; if (hasDeletedItems) { if (!confirm("There are client-side deletes! Would you like to save these changes to the server?")) { $find("<%= RadGrid1.ClientID %>")._deletedItems = []; $find("<%= RadGrid1.ClientID %>").updateClientState(); } } } </script> </telerik:RadCodeBlock><telerik:RadSkinManager ID="RadSkinManager1" Runat="server" Skin="Hay" ></telerik:RadSkinManager><telerik:RadFormDecorator ID="QsfFromDecorator" runat="server" DecoratedControls="All" EnableRoundedCorners="false" /><telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest"> <AjaxSettings> <telerik:AjaxSetting AjaxControlID="RadGrid1"> <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1"> </telerik:AjaxUpdatedControl> <telerik:AjaxUpdatedControl ControlID="RadInputManager1"></telerik:AjaxUpdatedControl> <telerik:AjaxUpdatedControl ControlID="Label1"></telerik:AjaxUpdatedControl> </UpdatedControls> </telerik:AjaxSetting> <telerik:AjaxSetting AjaxControlID="RadAjaxManager1"> <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1"> </telerik:AjaxUpdatedControl> <telerik:AjaxUpdatedControl ControlID="RadInputManager1"></telerik:AjaxUpdatedControl> <telerik:AjaxUpdatedControl ControlID="Label1"></telerik:AjaxUpdatedControl> </UpdatedControls> </telerik:AjaxSetting> </AjaxSettings> </telerik:RadAjaxManager> <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server"> </telerik:RadAjaxLoadingPanel><telerik:RadInputManager ID="RadInputManager1" EnableEmbeddedBaseStylesheet="false" Skin="" runat="server"> <telerik:TextBoxSetting BehaviorID="StringBehavior" InitializeOnClient="true" EmptyMessage="type here"> </telerik:TextBoxSetting> <telerik:NumericTextBoxSetting BehaviorID="CurrencyBehavior" EmptyMessage="type.." Type="Currency" Validation-IsRequired="true" MinValue="1" InitializeOnClient="true" MaxValue="100000"> </telerik:NumericTextBoxSetting> <telerik:NumericTextBoxSetting InitializeOnClient="true" BehaviorID="NumberBehavior" EmptyMessage="type.." Type="Number" DecimalDigits="0" MinValue="0" > </telerik:NumericTextBoxSetting> </telerik:RadInputManager> <div> <asp:Button ID="btnCommit" runat="server" Text="Commit" OnClick="btnCommit_Click" /> <span></span> <span><asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" /> </span> </div> <telerik:RadGrid ID="RadGrid1" Width="100%" ShowStatusBar="True" AllowSorting="True" PageSize="50" GridLines="Both" AllowPaging="True" runat="server" AutoGenerateColumns="False" OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCreated="RadGrid1_ItemCreated" OnCancelCommand="RadGrid1_CancelCommand" OnDeleteCommand="RadGrid1_DeleteCommand" OnUpdateCommand="RadGrid1_UpdateCommand" OnInsertCommand="RadGrid1_InsertCommand" OnItemInserted="RadGrid1_ItemInserted" EnableAJAX="True" OnItemDataBound="RadGrid1_ItemDataBound" > <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle> <MasterTableView TableLayout="Fixed" DataKeyNames="row_id" ClientDataKeyNames="row_id" CommandItemDisplay="Top" Width="100%" InsertItemDisplay="Top" InsertItemPageIndexAction="ShowItemOnFirstPage"> <CommandItemSettings ShowAddNewRecordButton="true"></CommandItemSettings> <CommandItemTemplate> <div style="height: 30px; text-align: right;"> <asp:Image ID="imgCancelChanges" runat="server" ImageUrl="~/Availability/Images/cancel.gif" AlternateText="Cancel changes" ToolTip="Cancel changes" Height="24px" Style="cursor: pointer; margin: 2px 5px 0px 0px;" onclick="CancelChanges();"></asp:Image> <asp:Image ID="imgProcessChanges" runat="server" ImageUrl="~/Availability/Images/ok.gif" AlternateText="Process changes" ToolTip="Process changes" Height="24px" Style="cursor: pointer; margin: 2px 5px 0px 0px;" onclick="ProcessChanges();"></asp:Image> </div> </CommandItemTemplate> <Columns> <telerik:GridButtonColumn HeaderStyle-Width="4%" UniqueName="Delete" ConfirmTextFormatString="Are you sure you want to delete details for row {0}?" CommandName="Delete" ImageUrl="~/Availability/Images/Delete.gif" ButtonType="ImageButton" ></telerik:GridButtonColumn> <telerik:GridTemplateColumn UniqueName="row_id" SortExpression="row_id" HeaderText="row_id" HeaderStyle-Width="5%" Visible="false"> <ItemTemplate> <asp:Label ID="lblrow_id" runat="server" Text='<%# Eval("row_id") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridBoundColumn UniqueName="ItemSku" DataField="Customer_Item_Sku" HeaderText="Item SKU" ReadOnly="True" HeaderStyle-Width="25%"> </telerik:GridBoundColumn> <telerik:GridTemplateColumn UniqueName="ItemDesc" SortExpression="ItemDesc" HeaderText="Item Description" HeaderStyle-Width="30%"> <ItemTemplate> <asp:Label ID="lblItemDesc" runat="server" Text='<%# Eval("customer_item_description") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="Six6" HeaderText="Six" SortExpression="Six" HeaderStyle-Width="2%"> <ItemTemplate> <asp:Label ID="lblSix" runat="server" Text='<%# Eval("quantity_on_hand_minus_6") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="Fiv5" HeaderText="Fiv" SortExpression="Fiv" HeaderStyle-Width="2%"> <ItemTemplate> <asp:Label ID="lblFiv" runat="server" Text='<%# Eval("quantity_on_hand_minus_5") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="For4" HeaderText="For" SortExpression="For" HeaderStyle-Width="2%"> <ItemTemplate> <asp:Label ID="lblFor" runat="server" Text='<%# Eval("quantity_on_hand_minus_4") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="Thr3" HeaderText="Thr" SortExpression="Thr" HeaderStyle-Width="2%"> <ItemTemplate> <asp:Label ID="lblThr" runat="server" Text='<%# Eval("quantity_on_hand_minus_3") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="Two2" HeaderText="Two" SortExpression="Two" HeaderStyle-Width="2%"> <ItemTemplate> <asp:Label ID="lblTwo" runat="server" Text='<%# Eval("quantity_on_hand_minus_2") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="One1" HeaderText="One" SortExpression="One" HeaderStyle-Width="2%"> <ItemTemplate> <asp:Label ID="lblOne" runat="server" Text='<%# Eval("quantity_on_hand_minus_1") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="Zer0" HeaderText="Zer" SortExpression="Zer" HeaderStyle-Width="2%"> <ItemTemplate> <asp:Label ID="lblZer" runat="server" Text='<%# Eval("quantity_on_hand_minus_0") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="pkgQty" HeaderText="Pkg Qty" SortExpression="pkgQty" HeaderStyle-Width="5%"> <ItemTemplate> <asp:Label ID="lblPkgQty" runat="server" Text='<%# Eval("package_quantity") %>'></asp:Label> <asp:TextBox ID="txtPkgQty" runat="server" Width="50px" Text='<%# Bind("package_quantity") %>' Style="display: none"></asp:TextBox> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="QtyAvail" HeaderText="Qty Avail" SortExpression="UnitsOnOrder" HeaderStyle-Width="10%"> <ItemTemplate> <asp:Label ID="lblQtyAvail" runat="server" Text='<%# Eval("Quantity_Available") %>'></asp:Label> <asp:TextBox ID="txtQtyAvail" runat="server" Text='<%# Bind("Quantity_Available") %>' Width="50px" Style="display: none"></asp:TextBox> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="Status" HeaderText="Status" SortExpression="UnitsOnOrder" HeaderStyle-Width="10%"> <ItemTemplate> <asp:Label ID="lblStatus" runat="server" Text='<%# Eval("Status") %>'></asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> </Columns> <CommandItemSettings AddNewRecordText="Add new record" ShowAddNewRecordButton="true" AddNewRecordImageUrl="Images/Add.PNG" RefreshText="Refresh" RefreshImageUrl="Images/Refresh.gif"></CommandItemSettings> </MasterTableView> <ClientSettings> <ClientEvents OnRowCreated="RowCreated" OnRowClick="RowClick" OnCommand="RadGrid1_Command" OnRowDestroying="RowDestroying" ></ClientEvents> </ClientSettings> </telerik:RadGrid> <br /> <asp:Label ID="Label1" runat="server" EnableViewState="false"></asp:Label> <br />
code behind is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
using BFNReportProject.DataClasses;
using BFNReportProject.CommonClasses;
using BFNReportProject.Controls;
using BFNReportProject.BFNRTR.RTRClasses;
namespace BFNReportProject.Controls
{
public partial class Blanket : System.Web.UI.UserControl
{
private DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
BindBlanketData();
}
private DataTable BindBlanketData()
{
// dt = RTRClass.GetBlanketTable("5", "21", "ZE", "1543", "OR1");
// dt = RTRClass.GetBlanketTable("5", "4", null, "3", "");
if (Session["BlanketTable"] == null)
dt = getData();
else
dt = ((DataTable)Session["BlanketTable"]);
if (dt.Rows.Count == 0)
{
//lblerror.Visible = true;
// lblerror.Text = "No Data Found";
}
Session["BlanketTable"] = dt;
return dt;
}
private DataTable getData()
{
DataTable table = new DataTable("TestTable");
table.Columns.Add("row_id", typeof(int));
table.Columns.Add("Customer_Item_Sku", typeof(string));
table.Columns.Add("customer_item_description", typeof(string));
table.Columns.Add("quantity_on_hand_minus_6", typeof(string));
table.Columns.Add("quantity_on_hand_minus_5", typeof(string));
table.Columns.Add("quantity_on_hand_minus_4", typeof(string));
table.Columns.Add("quantity_on_hand_minus_3", typeof(string));
table.Columns.Add("quantity_on_hand_minus_2", typeof(string));
table.Columns.Add("quantity_on_hand_minus_1", typeof(string));
table.Columns.Add("quantity_on_hand_minus_0", typeof(string));
table.Columns.Add("package_quantity", typeof(Int32));
table.Columns.Add("Quantity_Available", typeof(Int32));
table.Columns.Add("Status", typeof(string));
for (int i = 0; i <= 10; i++)
{
table.Rows.Add(i, "ItemSku" + i, "ItemDesc" + i, "6" , "5" , "4" , "3" , "2" , "1" , "0" , i + 2, i + 100);
}
dt = table;
return dt;
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = BindBlanketData();
}
private void SetMessage(string message)
{
Label1.Text = string.Format("<span>{0}</span>", message);
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem dataItem = (GridDataItem)e.Item;
TextBox txtBox = (TextBox)dataItem.FindControl("txtPkgQty");
NumericTextBoxSetting numberSetting = (NumericTextBoxSetting)RadInputManager1.GetSettingByBehaviorID("NumberBehavior");
numberSetting.TargetControls.Add(new TargetInput(txtBox.UniqueID, true));
Label lblStatus = (Label)dataItem.FindControl("lblStatus");
string txt = lblStatus.Text;
if (lblStatus.Text == "Delete")
dataItem.Visible = false;
}
}
protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
{
if (e.Argument == string.Empty)
{
RadGrid1.Rebind();
}
string[] editedItemIds = e.Argument.Split(':');
int i;
for (i = 0; i <= editedItemIds.Length - 2; i++)
{
string rowId = editedItemIds[i];
GridDataItem updatedItem = RadGrid1.MasterTableView.FindItemByKeyValue("row_id", int.Parse(rowId));
UpdateValues(updatedItem);
}
}
protected void UpdateValues(GridDataItem updatedItem)
{
if (updatedItem != null)
{
Label labelBox = (Label)updatedItem.FindControl("lblrow_id");
string rowId = labelBox.Text;
TextBox txtBox = (TextBox)updatedItem.FindControl("txtPkgQty");
string editedPkgQty = txtBox.Text;
txtBox = (TextBox)updatedItem.FindControl("txtQtyAvail");
string editedQtyAvail = txtBox.Text;
// SqlDataSource1.UpdateParameters["ProductID"].DefaultValue = updatedItem.GetDataKeyValue("ProductID").ToString();
try
{
dt = (DataTable)Session["BlanketTable"];
DataRow[] tableRow = dt.Select("row_id= "+ Convert.ToInt32(rowId));
tableRow[0]["package_quantity"]= editedPkgQty;
tableRow[0]["Quantity_Available"]= editedQtyAvail;
tableRow[0]["Status"] = "updated";
Session["BlanketTable"] = dt;
// SqlDataSource1.Update();
}
catch (Exception ex)
{
SetMessage(Server.HtmlEncode("Unable to update Products. Reason: " + ex.StackTrace).Replace("'", "'").Replace("\r\n", "<br />"));
}
SetMessage("Product with ID: " + updatedItem.GetDataKeyValue("row_id") + " updated");
RadGrid1.Rebind();
}
}
protected void btnCommit_Click(object sender, EventArgs e)
{
dt.AcceptChanges();
}
protected void btnSave_Click(object sender, EventArgs e)
{
dt = (DataTable)Session["BlanketTable"];
System.IO.StringWriter writer = new System.IO.StringWriter();
//notice that we're ignoring the schema so we get clean XML back
//you can change the write mode as needed to get your result
dt.WriteXml(writer, XmlWriteMode.IgnoreSchema, false);
string dataTableXml = writer.ToString();
// save the XML in database.
// dt.WriteXml(@"c:\Replenishment.xml");
}
protected void RadGrid1_CancelCommand(object sender, GridCommandEventArgs e)
{
}
protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
{
}
protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
{
//Get the GridDataItem of the RadGrid
GridDataItem item = (GridDataItem)e.Item;
//Get the primary key value using the DataKeyValue.
string row_id = item.OwnerTableView.DataKeyValues[item.ItemIndex]["row_id"].ToString();
try
{
dt = (DataTable)Session["BlanketTable"];
DataRow[] tableRow = dt.Select("row_id=" + Convert.ToInt32(row_id));
foreach(var row in tableRow)
{
tableRow[0]["Status"] = "Delete";
}
Session["BlanketTable"] = dt;
}
catch (Exception ex)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to delete Employee. Reason: " + ex.Message));
e.Canceled = true;
}
}
protected void RadGrid1_ItemInserted(object sender, GridInsertedEventArgs e)
{
}
protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
//Get the GridEditFormInsertItem of the RadGrid
GridEditFormInsertItem insertedItem = (GridEditFormInsertItem)e.Item;
//string EmployeeID = (insertedItem["EmployeeID"].Controls[0] as TextBox).Text;
/* string LastName = (insertedItem["LastName"].Controls[0] as TextBox).Text;
string FirstName = (insertedItem["FirstName"].Controls[0] as TextBox).Text;
string Title = (insertedItem["Title"].Controls[0] as TextBox).Text;
string Address = (insertedItem["Address"].Controls[0] as TextBox).Text;
string City = (insertedItem["City"].Controls[0] as TextBox).Text;*/
try
{
}
catch (Exception ex)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to insert Employee. Reason: " + ex.Message));
e.Canceled = true;
}
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem dataItem = (GridDataItem)e.Item;
Label lblStatus = (Label)dataItem.FindControl("lblStatus");
string txt = lblStatus.Text;
if (lblStatus.Text == "Delete")
dataItem.Visible = false;
}
}
}
}
I noted that you have declarated the CommandItemSettings in to places of your code, avoid that, place them in one place.
<CommandItemSettings ShowAddNewRecordButton="true"></CommandItemSettings>.......<CommandItemSettings AddNewRecordText="Add new record" ShowAddNewRecordButton="true" AddNewRecordImageUrl="Images/Add.PNG" RefreshText="Refresh" RefreshImageUrl="Images/Refresh.gif"></CommandItemSettings>Second thing is that if you use CommandItemTemplate, then you will see only the template, without the default buttons in the settings. In case you are using the template, place an AddButton inside your template as it is done in this help article:
http://www.telerik.com/help/aspnet-ajax/grid-commanditemtemplate.html
All the best,
Vasil
the Telerik team