Update row in Gridview? - c#-4.0

I have updated a row in Gridview but it is not working.
Here is my code :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
//Label lbldeleteid = (Label)row.FindControl("Label1");
string bname= GridView1.DataKeys[e.RowIndex].Values["manufacturer"].ToString();
TextBox tbmanu = (TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[1];
var myString = tbmanu.ToString();
SqlCommand cmd = new SqlCommand("manu_upd",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#manufacturer", SqlDbType.NVarChar,100);
cmd.Parameters["#manufacturer"].Value = myString;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
I got the following error :
Unable to cast object of type 'System.Web.UI.LiteralControl' to type
'System.Web.UI.WebControls.TextBox'.
here is my Grid view :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="manufacturer" ForeColor="#333333"
GridLines="None" Width="400px" BorderStyle="Double"
CellSpacing="3" Font-Bold="True" Font-Size="Small" ShowFooter="True"
ShowHeaderWhenEmpty="True" onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
onrowcancelingedit="GridView1_RowCancelingEdit"
AutoGenerateEditButton="True">
<AlternatingRowStyle BackColor="White"/>
<Columns>
<asp:TemplateField HeaderText="Number" ItemStyle-
HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lbnaumber" runat="server" Text='<%#
Container.DataItemIndex + 1 %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Manufacturer"
SortExpression="manufacturer">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#
Bind("manufacturer") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbmanu" runat="server" Text='<%#
Bind("manufacturer") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<EditRowStyle BackColor="#2461BF"/><FooterStyle BackColor="#507CD1"
Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"/>
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" /><SelectedRowStyle BackColor="#D1DDF1"
Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB"/>
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
When I change the index of my text box 1 to 3 it shows me below error :
Specified argument was out of the range of valid values.
Parameter name: index
When i change its index 3 to 2 it gives me below error :
Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.
I have one required field validator in my form but when I enable that validation update in grid view is not working.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox tbmanu1 = (TextBox)row.FindControl("tbmanu");
//or try
//TextBox tbmanu1= (TextBox)row.Cells[0].FindControl("tbmanu");
string myString = Convert.Tostring(tbmanu1.text);
cmd.Parameters["#manufacturer"].Value = myString;
}

Try wrapping your gridview in a asp:UpdatePanel and set the update mode to conditional.
Good Luck

Related

MultiSelect Dropdown in Acumtica

I have some problems with the fact that when I select a value in the dropbox, or rather steel a checkmark, then it is automatically reset.
[Serializable]
public class KNRWCSAttributeExt : PXCacheExtension<CSAttribute>
{
public static bool IsActive() => true;
#region UsrSchemaField
[PXDBString(512, InputMask = "", IsUnicode = true)]
[PXUIField(DisplayName = "Multi Schema Field")]
//[PXUIVisible(typeof(Where<PX.CS.CSAttribute.controlType, Equal<CSAttribute.AttrType.giSelector>>))]
[PXStringList(new string[] {null}, new string[] {""}, ExclusiveValues = false)]
public virtual string UsrSchemaField { get; set; }
public abstract class usrSchemaField : PX.Data.BQL.BqlString.Field<usrSchemaField>
{
}
#endregion
}
I assume that this is due to the fact that the event is triggered again and the array is filled over and over again. With the usual examples that are already described on stackoverflow it works, but my code does not work
Tell me please how I can get data into DropDown once so that I can then select and the value is not reset.
public class KNRWCSAttributeMaintExt : PXGraphExtension<CSAttributeMaint>
{
public static bool IsActive() => true;
protected virtual void _(Events.RowSelected<CSAttribute> e)
{
if (e.Row == null)
{
return;
}
var el = e.Row as CSAttribute;
if (el.ControlType == CSAttribute.GISelector)
{
if (!string.IsNullOrEmpty(e.Row.ObjectName as string))
{
Type objType = System.Web.Compilation.PXBuildManager.GetType(e.Row.ObjectName, true);
PXCache objCache = Base.Caches[objType];
var fields = objCache.Fields
.Where(f => objCache.GetBqlField(f) != null ||
f.EndsWith("_Attributes", StringComparison.OrdinalIgnoreCase))
.Where(f => !objCache.GetAttributesReadonly(f).OfType<PXDBTimestampAttribute>().Any())
.Where(f => !string.IsNullOrEmpty((objCache.GetStateExt(null, f) as PXFieldState)?.ViewName))
.Where(f => f != "CreatedByID" && f != "LastModifiedByID")
.ToArray();
PXStringListAttribute.SetList<KNRWCSAttributeExt.usrSchemaField>(e.Cache, e.Row, fields, fields);
}
}
}
}
View
<asp:Content ID="cont2" ContentPlaceHolderID="phF" runat="Server">
<px:PXFormView ID="form" runat="server" DataSourceID="ds" Style="z-index: 100" Width="100%" DataMember="Attributes" Caption="Attribute Summary">
<Template>
<px:PXLayoutRule runat="server" StartColumn="True" ControlSize="M" LabelsWidth="SM" />
<px:PXSelector ID="edAttributeID" runat="server" DataField="AttributeID" AutoRefresh="True" DataSourceID="ds">
<GridProperties FastFilterFields="description" />
</px:PXSelector>
<px:PXTextEdit ID="edDescription" runat="server" AllowNull="False" DataField="Description" />
<px:PXDropDown CommitChanges="True" ID="edControlType" runat="server" AllowNull="False" DataField="ControlType" />
<px:PXCheckBox ID="chkIsInternal" runat="server" DataField="IsInternal" />
<px:PXCheckBox ID="chkContainsPersonalData" runat="server" DataField="ContainsPersonalData" />
<px:PXTextEdit ID="edEntryMask" runat="server" DataField="EntryMask" />
<px:PXTextEdit ID="edRegExp" runat="server" DataField="RegExp" />
<px:PXSelector ID="SchemaObject" runat="server" DataField="ObjectName" AutoRefresh="True" CommitChanges="true" />
<px:PXDropDown ID="SchemaField" runat="server" DataField="FieldName" AutoRefresh="True" CommitChanges="True" />
<px:PXDropDown ID="edRegExpMultiSelect" runat="server" AllowMultiSelect="true" DataField="UsrSchemaField" CommitChanges="True"/>
</Template>
</px:PXFormView>
</asp:Content>
Having the field value disappear just means that the custom field was not correctly implemented. When the system can't select/persist a record or a field it disappears when control focus is lost.
The DAC field type appears to be wrong. Usually string list uses small codes of about 2 or 3 letters string with fixed size:
[PXDBString(3, IsFixed = true)]
Since you are setting the list dynamically you don't need to define null string values in the DAC:
[PXStringList]
You need to make sure that your event is always providing the expected code values. This can be checked by removing the conditions and using constants for the SetList method call:
https://stackoverflow.com/a/38089639/7376238
Maybe you missed some steps like creating the field in the database table. You can test with an unbound PXString field instead of a PXDBString like in this example to see if that's the issue:
https://stackoverflow.com/a/49907964/7376238
Thanks for the help, I solved the problem by replacing "e.Row" with "null" in this line
before:
PXStringListAttribute.SetList<KNRWCSAttributeExt.usrSchemaField>(e.Cache, e.Row, fields, fields);
after:
PXStringListAttribute.SetList<KNRWCSAttributeExt.usrSchemaField>(e.Cache, null, fields, fields);

How to refresh a grid from a redirected page

I have an inquiry page where the Header is the POLine table and the grid is a new table linked to POLine. I cannot use an unbounded DAC for the filters because I want to offer the option to navigate over existing records.
If I open the page directly and enter the POLine information, the grid is refreshed correctly.
I included a button in the Purchase Orders page with an action that opens my inquiry page. In this scenario, the filter is loaded correctly but the grid does not show the records until the grid's refresh button is pressed.
This is my Action:
public PXAction<POOrder> Reconcile;
[PXUIField(DisplayName = "Reconcile", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select)]
[PXButton(CommitChanges = true, OnClosingPopup = PXSpecialButtonType.Cancel)]
public virtual void reconcile()
{
POLine pOLineRow = Transactions.Current;
if (pOLineRow == null)
{
return;
}
if (pOLineRow.OrderNbr != null)
{
PEPOOrderReconciliationMaint pEPOOrderReconciliationgraph = PXGraph.CreateInstance<PEPOOrderReconciliationMaint>();
pEPOOrderReconciliationgraph.POOrderReconcileRecord.Current = pEPOOrderReconciliationgraph.POOrderReconcileRecord.Search<POLine.orderType, POLine.orderNbr, POLine.lineNbr>(pOLineRow.OrderType, pOLineRow.OrderNbr, pOLineRow.LineNbr, pOLineRow.OrderType);
if (pEPOOrderReconciliationgraph.POOrderReconcileRecord.Current != null)
{
throw new PXRedirectRequiredException(pEPOOrderReconciliationgraph, false, "PORECONCILIATION") { Mode = PXBaseRedirectException.WindowMode.NewWindow };
}
}
}
I have not used the Search<> method at a detail level before, but I found this Acumatica reference in POReceiptEntry:
POLineR polineR = _graph.purchaseLinesUPD.Search<POLineR.orderType, POLineR.orderNbr, POLineR.lineNbr>
(itemsource.OrderType, itemsource.OrderNbr, itemsource.LineNbr);
I also tried to assign the value directly with a PXSelect:
pEPOOrderReconciliationgraph.POOrderReconcileRecord.Current = PXSelect<POLine,Where<POLine.orderType,
Equal<Required<POLine.orderType>>,And<POLine.orderNbr,
Equal<Required<POLine.orderNbr>>,And<POLine.lineNbr,
Equal<Required<POLine.lineNbr>>>>>>
.Select(this, pOLineRow.OrderType, pOLineRow.OrderNbr, pOLineRow.LineNbr);
I don't think this is related to the error though. I think it's more oriented to a refresh option in the ASPX.
This is my ASPX code:
<%# Page Language="C#" MasterPageFile="~/MasterPages/FormDetail.master" AutoEventWireup="true" ValidateRequest="false" CodeFile="PR501000.aspx.cs" Inherits="Page_PR501000" Title="Untitled Page" %>
<%# MasterType VirtualPath="~/MasterPages/FormDetail.master" %>
<asp:Content ID="cont1" ContentPlaceHolderID="phDS" Runat="Server">
<px:PXDataSource ID="ds" runat="server" Visible="True" Width="100%" TypeName="Purchase.PEPOOrderReconciliationMaint" PrimaryView="POOrderReconcileRecord">
<CallbackCommands>
<px:PXDSCallbackCommand Name="SaveClose" Visible="false" PopupVisible="false"/>
<px:PXDSCallbackCommand Name="Save" Visible="false" CommitChanges="true"/>
<px:PXDSCallbackCommand Name="Cancel" Visible="true" CommitChanges="true"/>
<px:PXDSCallbackCommand Name="Insert" Visible="false" CommitChanges="true"/>
<px:PXDSCallbackCommand Name="CopyPaste" Visible="false" CommitChanges="true"/>
<px:PXDSCallbackCommand Name="Delete" Visible="false" CommitChanges="true"/>
</CallbackCommands>
</px:PXDataSource>
</asp:Content>
<asp:Content ID="cont2" ContentPlaceHolderID="phF" Runat="Server">
<px:PXFormView ID="form" runat="server" DataSourceID="ds" Style="z-index: 100"
Width="100%" DataMember="POOrderReconcileRecord" TabIndex="4500">
<Template>
<px:PXLayoutRule runat="server" StartColumn="True">
</px:PXLayoutRule>
<px:PXDropDown ID="edOrderType" runat="server" DataField="OrderType">
</px:PXDropDown>
<px:PXSelector ID="edOrderNbr" runat="server" DataField="OrderNbr" AutoRefresh="True" CommitChanges="True">
</px:PXSelector>
<px:PXLayoutRule runat="server" StartColumn="True"/>
<px:PXSelector ID="edLineNbr" runat="server" CommitChanges="True" DataField="LineNbr">
</px:PXSelector>
</Template>
</px:PXFormView>
</asp:Content>
<asp:Content ID="cont3" ContentPlaceHolderID="phG" Runat="Server">
<px:PXGrid ID="grid" runat="server" DataSourceID="ds" Style="z-index: 100; margin-top: 0px;"
Width="100%" Height="150px" SkinID="Details" TabIndex="21000" KeepPosition="True" SyncPosition="True" AdjustPageSize="Manual">
<Levels>
<px:PXGridLevel DataKeyNames="OrderType,OrderNbr,LineNbr" DataMember="POReceiptLineRecord">
<RowTemplate>
<px:PXSegmentMask ID="edInventoryID" runat="server" DataField="InventoryID" CommitChanges="True" Size="M" Width="200px">
</px:PXSegmentMask>
<px:PXNumberEdit ID="edReceiptQty" runat="server" AlreadyLocalized="False" DataField="ReceiptQty" CommitChanges="True" Size="S">
</px:PXNumberEdit>
</RowTemplate>
<Columns>
<px:PXGridColumn DataField="InventoryID">
</px:PXGridColumn>
<px:PXGridColumn DataField="ReceiptQty" TextAlign="Right" Width="100px">
</px:PXGridColumn>
</Columns>
</px:PXGridLevel>
</Levels>
<AutoSize Container="Window" Enabled="True" MinHeight="150" />
</px:PXGrid>
</asp:Content>
This is the PEPOOrderReconciliationMaint code:
public class PEPOOrderReconciliationMaint : PXGraph<PEPOOrderReconciliationMaint, POLine>
{
public PXSelect<POLine> POOrderReconcileRecord;
public PXSelect<POReceiptLine,
Where<
POReceiptLine.pOType, Equal<Current<POLine.orderType>>,
And<POReceiptLine.pONbr, Equal<Current<POLine.orderNbr>>,
And<POReceiptLine.pOLineNbr, Equal<Current<POLine.lineNbr>>>>>> POReceiptLineRecord;
#region Cache Attached
#region OrderType
[PXDBString(2, IsFixed = true, IsKey = true)]
[POOrderType.List()]
[PXUIField(DisplayName = "Type", Enabled = true)]
protected virtual void POLine_OrderType_CacheAttached(PXCache Sender)
{
}
#endregion
#region OrderNbr
[PXDBString(15, IsUnicode = true, InputMask = "", IsKey = true)]
[PXUIField(DisplayName = "Order Nbr.", Visible = true)]
[PXSelector(typeof(Search<POOrder.orderNbr,
Where<POOrder.orderType, Equal<Current<POLine.orderType>>>>))]
protected virtual void POLine_OrderNbr_CacheAttached(PXCache Sender)
{
}
#endregion
#region LineNbr
[PXDBInt(IsKey = true)]
[PXUIField(DisplayName = "Line Nbr.", Visible = true, Enabled = true)]
[PXSelector(typeof(Search<POLine.lineNbr,
Where<POLine.orderNbr, Equal<Current<POLine.orderNbr>>,
And<POLine.orderType, Equal<Current<POLine.orderType>>>>>))]
protected virtual void POLine_LineNbr_CacheAttached(PXCache Sender)
{
}
#endregion
#endregion
}

How to bind dropdownlist in radgrid

I am new to use telerik controls. I want to bind data in dropdownlist that is in telerik RadGrid control. I have already been applied but it gives an error
Object reference not set to an instance of an object.
Here is my code given below :
Source code
<telerik:RadGrid runat="server" ID="RadGrid1" AutoGenerateColumns="false" AllowPaging="true"
OnNeedDataSource="RadGrid1_NeedDataSource" OnUpdateCommand="RadGrid1_UpdateCommand"
OnItemCreated="RadGrid1_ItemCreated" OnDeleteCommand="RadGrid1_DeleteCommand"
OnInsertCommand="RadGrid1_InsertCommand"
onitemdatabound="RadGrid1_ItemDataBound" >
<MasterTableView DataKeyNames="id" CommandItemDisplay="Top" InsertItemPageIndexAction="ShowItemOnCurrentPage">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" />
<telerik:GridBoundColumn DataField="id" HeaderText="ID" ReadOnly="true"
ForceExtractValue="Always" ConvertEmptyStringToNull="true" />
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="ddldept" DataTextField="name" DataValueField="id" runat="server"></asp:DropDownList>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="code" HeaderText="Branch Code" />
<telerik:GridBoundColumn DataField="name" HeaderText="Branch Name" />
<telerik:GridBoundColumn DataField="shortname" HeaderText="Branch Shorth Name" />
<telerik:GridBoundColumn DataField="hod" HeaderText="Head of Department"/>
<telerik:GridBoundColumn DataField="location" HeaderText="Location Address" />
<telerik:GridButtonColumn ConfirmText="Are you sure want to delete this Branch?" ConfirmDialogType="RadWindow"
ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" />
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
</MasterTableView>
<PagerStyle Mode="NextPrevAndNumeric" />
<ClientSettings>
<ClientEvents OnRowDblClick="rowDblClick" />
</ClientSettings>
</telerik:RadGrid>
Main Code
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
DataTable dt=obj.display_branch();
GridEditableItem item = e.Item as GridEditableItem;
DropDownList list = item.FindControl("ddldept") as DropDownList;
list.DataSource = dt;
list.DataTextField = "name";
list.DataValueField = "id";
list.DataBind();
}
Try on RadGrid1_ItemCreated. That is how I achieved it.

Access Detail Table datakeynames on rowdrop event telerik

I am using telerik nested rad grid. Please take a look at code.
<telerik:RadGrid ID="radGridRoutes" runat="server" AutoGenerateColumns="false" ShowStatusBar="True"
AllowSorting="True" AllowPaging="True" ClientSettings-Scrolling-EnableVirtualScrollPaging="false"
ClientSettings-Scrolling-AllowScroll="false"
OnNeedDataSource="Routes_NeedDataSource" OnDetailTableDataBind="radGridRoutes_DetailTableDataBind" AllowFilteringByColumn="True"
EnableLinqExpressions="false" OnInsertCommand="Routes_InsertCommand"
OnUpdateCommand="radGridRoutes_UpdateCommand"
OnItemCommand="radGridRoutes_ItemCommand"
OnPreRender="radGridRoutes_PreRender" ClientSettings-AllowRowsDragDrop="true"
OnRowDrop="radGridRoutes_RowDrop">
<ClientSettings AllowDragToGroup="True">
<Selecting AllowRowSelect="True" />
</ClientSettings>
<GroupingSettings CaseSensitive="false" />
<SelectedItemStyle CssClass="SelectedItem" />
<PagerStyle Mode="NextPrevNumericAndAdvanced"></PagerStyle>
<ValidationSettings CommandsToValidate="PerformInsert,Update" EnableModelValidation="true"
EnableValidation="true" />
<FilterItemStyle BackColor="#F8F8F8" HorizontalAlign="Left" />
<FilterMenu EnableImageSprites="false">
</FilterMenu>
<MasterTableView DataKeyNames="ID" AllowMultiColumnSorting="false"
Width="100%" CommandItemDisplay="Top" Name="Routes">
<AlternatingItemStyle BackColor="WhiteSmoke" />
<DetailTables>
<telerik:GridTableView OnRowDrop="radGridRoutes_RowDrop" ClientSettings-AllowRowsDragDrop="true"
DataKeyNames="ID,DisplayOrder,RouteID" Width="100%" runat="server"
CommandItemDisplay="Top" Name="Stops" AllowFilteringByColumn="false">
<CommandItemSettings AddNewRecordText="Add New Stops" ShowAddNewRecordButton="true" />
<ParentTableRelation>
<%-- <telerik:GridRelationFields DetailKeyField="ID" MasterKeyField="ID" />--%>
</ParentTableRelation>
<RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
</RowIndicatorColumn>
<ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
</ExpandCollapseColumn>
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditTask" EditText="Edit"
UpdateText="Update" CancelText="Cancel">
<HeaderStyle Width="20px" />
</telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn SortExpression="Name" HeaderText="Name" UniqueName="Name"
HeaderButtonType="TextButton" HeaderStyle-Width="15%" ItemStyle-Width="15%" DataField="tName">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Width="250px" Text='<%# Eval("Name")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="requiredName" ControlToValidate="txtName"
CssClass="validationMessage" ErrorMessage="Name is required."
Text="* required" runat="server" Display="Dynamic"></asp:RequiredFieldValidator>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Comment" HeaderText="Comment" UniqueName="Comment"
HeaderButtonType="TextButton" DataField="Comment">
<ItemTemplate>
<%# Eval("Comment")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" TextMode="MultiLine" Rows="4" Width="250px" runat="server" Text='<%# Eval("Comment")%>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Address" HeaderText="Address"
DataField="Address" UniqueName="Address" HeaderButtonType="TextButton">
<ItemTemplate>
<%# Eval("Address")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAddress" Width="250px" TextMode="MultiLine" Text='<%# Bind("Address") %>' runat="server"></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Phone" HeaderText="Phone" UniqueName="Phone"
HeaderButtonType="TextButton" DataField="Phone">
<ItemTemplate>
<%# Eval("Phone")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPhone" Rows="4" Width="250px" runat="server" Text='<%# Eval("Phone")%>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Email" HeaderText="Email" UniqueName="Email"
HeaderButtonType="TextButton" DataField="Email">
<ItemTemplate>
<%# Eval("Email")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmail" Rows="4" Width="250px" runat="server" Text='<%# Eval("Email")%>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="ManagerName" HeaderText="ManagerName" UniqueName="ManagerName"
HeaderButtonType="TextButton" DataField="ManagerName">
<ItemTemplate>
<%# Eval("ManagerName")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtManagerName" Rows="4" Width="250px" runat="server" Text='<%# Eval("ManagerName")%>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="NumberOfRooms" HeaderText="#Rooms" UniqueName="NumberOfRooms"
HeaderButtonType="TextButton" DataField="NumberOfRooms">
<ItemTemplate>
<%# Eval("NumberOfRooms")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNumberOfRooms" Width="250px" Rows="4" runat="server" Text='<%# Eval("NumberOfRooms")%>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Merchandising" HeaderText="Merchandising" UniqueName="Merchandising"
HeaderButtonType="TextButton" DataField="Merchandising">
<ItemTemplate>
<%# Eval("Merchandising")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMerchandising" Width="250px" Rows="4" runat="server" Text='<%# Eval("Merchandising")%>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Frequency" HeaderText="Frequency"
DataField="Frequency" UniqueName="Frequency" HeaderButtonType="TextButton">
<ItemTemplate>
<%# GetFrequencyName(Convert.ToInt32(Eval("FrequencyID"))) %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpFreq" runat="server" DataTextField="Name" DataValueField="ID"
AppendDataBoundItems="true">
<asp:ListItem Text="--Select--" Value="-1">
</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="DisplayOrder" HeaderText="Display Order" UniqueName="DisplayOrder"
HeaderButtonType="TextButton" HeaderStyle-Width="15%" ItemStyle-Width="15%" DataField="DisplayOrder">
<ItemTemplate>
<%# Eval("DisplayOrder")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDisplayOrder" runat="server" Width="250px" Text='<%# Eval("DisplayOrder")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="requiredDisplayOrder" ControlToValidate="txtDisplayOrder"
CssClass="validationMessage" ErrorMessage="Display Order is required."
Text="* required" runat="server" Display="Dynamic"></asp:RequiredFieldValidator>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Delete" AllowFiltering="false">
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" CommandName="DeleteStops" CommandArgument=' <%# Eval("ID") %>' runat="server" OnClientClick="javascript:if (!confirm('Are you sure you want to delete Stop?')) {
return false;
}">Delete</asp:LinkButton>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column">
</EditColumn>
</EditFormSettings>
</telerik:GridTableView>
</DetailTables>
<RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
</RowIndicatorColumn>
<ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
</ExpandCollapseColumn>
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" CancelText="Cancel" EditText="Edit"
UpdateText="Update" UniqueName="EditRoutes" ItemStyle-Width="5%">
<HeaderStyle Width="5%" />
</telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn SortExpression="Name" HeaderText="Name" UniqueName="RouteName"
HeaderButtonType="TextButton" HeaderStyle-Width="20%" ItemStyle-Width="20%" DataField="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRouteName" runat="server" Text='<%# Eval("Name")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="requiredRouteName" ControlToValidate="txtRouteName"
CssClass="validationMessage" ErrorMessage="Name is required."
Text="* required" runat="server" Display="Dynamic"></asp:RequiredFieldValidator>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Comment" HeaderText="Comment" UniqueName="Comment"
HeaderButtonType="TextButton" DataField="Comment">
<ItemTemplate>
<%# Eval("Comment")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" TextMode="MultiLine" Rows="4" Width="250px" runat="server" Text='<%# Eval("Comment")%>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Delete" AllowFiltering="false">
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" CommandName="Delete" CommandArgument=' <%# Eval("ID") %>' runat="server" OnClientClick="javascript:if (!confirm('Are you sure you want to delete route?')) {
return false;
}">Delete</asp:LinkButton>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<SortExpressions>
<telerik:GridSortExpression FieldName="Name"></telerik:GridSortExpression>
</SortExpressions>
<CommandItemSettings AddNewRecordText="Add New Route" ShowAddNewRecordButton="true" />
<EditFormSettings>
<EditColumn UniqueName="EditCommandColumn1" FilterControlAltText="Filter EditCommandColumn1 column">
</EditColumn>
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>
And the code behind rowDrop event is
protected void radGridRoutes_RowDrop(object sender, GridDragDropEventArgs e)
{
GridDataItem RowDragged = e.DraggedItems.FirstOrDefault();
e.DraggedItems[0].GetDataKeyValue("DisplayOrder");
int OriginalID = Convert.ToInt32(RowDragged.GetDataKeyValue("ID"));
int OriginalOrder = Convert.ToInt32(RowDragged.GetDataKeyValue("DisplayOrder"));
int RouteID = Convert.ToInt32(RowDragged.GetDataKeyValue("RouteID"));
int DestID = Convert.ToInt32(e.DestDataItem.GetDataKeyValue("ID"));
int DestOrder = Convert.ToInt32(e.DestDataItem.GetDataKeyValue("DisplayOrder"));
UpdateOrder(OriginalID, OriginalOrder, DestID, RouteID);
}
Now the problem is i want to access the datakeyNames from the nested gridTableView. I am not able to figure that out. Please provide me suggestions how to get the ID,DisplayOrder,RouteID from nested gridtableview in rowdrop event. Currently it is giving null values to me.
Please try with the below code snippet.
ASPX
<telerik:GridTableView Name="Child" OnRowDrop="radGridRoutes_RowDrop" ClientSettings-AllowRowsDragDrop="true" DataKeyNames="ID,DisplayOrder,RouteID" Width="100%" runat="server" CommandItemDisplay="Top" Name="Stops" AllowFilteringByColumn="false">
ASPX.CS
protected void radGridRoutes_RowDrop(object sender, GridDragDropEventArgs e)
{
GridDataItem RowDragged = e.DraggedItems.FirstOrDefault();
if (RowDragged.OwnerTableView.Name == "Child")
{
// Row Dragged from child Grid
e.DraggedItems[0].GetDataKeyValue("DisplayOrder");
int OriginalID = Convert.ToInt32(RowDragged.GetDataKeyValue("ID"));
int OriginalOrder = Convert.ToInt32(RowDragged.GetDataKeyValue("DisplayOrder"));
int RouteID = Convert.ToInt32(RowDragged.GetDataKeyValue("RouteID"));
// You can also check same thing for Drop Item
int DestID = Convert.ToInt32(e.DestDataItem.GetDataKeyValue("ID")); int DestOrder = Convert.ToInt32(e.DestDataItem.GetDataKeyValue("DisplayOrder"));
UpdateOrder(OriginalID, OriginalOrder, DestID, RouteID);
}
}
Update 1:
If above code is not working then please try with the below code snippet.
Method 1:
ASPX
<telerik:GridTableView Name="Child" ClientDataKeyNames="ID,DisplayOrder,RouteID" OnRowDrop="radGridRoutes_RowDrop" ClientSettings-AllowRowsDragDrop="true" DataKeyNames="ID,DisplayOrder,RouteID" Width="100%" runat="server" CommandItemDisplay="Top" Name="Stops" AllowFilteringByColumn="false">
......
......
<ClientSettings>
<ClientEvents OnRowDragStarted="RowDragStarted" />
</ClientSettings>
JS Code
function RowDragStarted(sender, eventArgs) {
var tblvew = eventArgs.get_tableView().get_name();
if(tblvew == null || tblvew == undefined || tblvew != 'Child')
{
eventArgs.set_cancel(true);
}
}
OR
function RowDragStarted(sender, eventArgs) {
var route = eventArgs.getDataKeyValue("RouteID");
if(route == null || route == '')
{
eventArgs.set_cancel(true);
}
}
Let me know if any concern.

Gridview to excel: The Controls collection cannot be modified because the control contains code blocks

I'm getting error "The Controls collection cannot be modified because the control contains code blocks."
I want to Export GridView to Excel.
My method is: (it works I've tested it)
private void excel()
{
string dosyaadi;
dosyaadi = "Rapor.xls";
String attachment = "attachment; filename=" + dosyaadi;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
Response.Charset = "windows-1254";
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
gvListele.Parent.Controls.Add(frm);
frm.Controls.Add(gvListele);
frm.RenderControl(htw);
Response.Write(" <meta http-equiv='Content-Type' content='text/html; charset=windows-1254' />" + sw.ToString());
Response.End();
}
And gridview :
<asp:GridView ID="gvListele" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<Columns>
<asp:BoundField DataField="talepNo" HeaderText="Talep No" />
<asp:BoundField DataField="urunAdi" HeaderText="İçerik" />
<asp:BoundField DataField="talepEdenBirim" HeaderText="Talep Eden Birim" />
<asp:BoundField DataField="talepKomisyonGelisTarih" HeaderText="Komisyona Geliş Tarihi" />
<asp:BoundField DataField="alimUsulu" HeaderText="Alım Usulü" />
<asp:TemplateField ControlStyle-Width="150" HeaderText="Onay">
<ItemTemplate>
<asp:RadioButton ID="rbOnaylandi" runat="server" Text="Onaylandı" GroupName="rblOnay" />
<asp:RadioButton ID="rbBekletildi" runat="server" Text="Bekletildi" GroupName="rblOnay" />
<asp:RadioButton ID="rbReddedildi" runat="server" Text="Reddedildi" GroupName="rblOnay" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
I think this may be because you're trying to add your GridView to a new HtmlForm, you can export without doing this. Try the following example, and extend as necessary:
protected void excel()
{
String dosyaadi = "Rapor.xls";
Response.Clear();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + dosyaadi + ".xls");
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Also ensure you have this override function in your C# codebehind:
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

Resources