How to create separate DetailTable on each row in a RadGrid? - telerik

I have a telerik radgrid where columns and detail tables are declared like:
<telerik:RadGrid>
<Columns>
<telerik:GridBoundColumn/>
<telerik:GridBoundColumn/>
</Columns>
<DetailTables>
<telerik:GridTableView
<Columns>
<telerik:GridBoundColumn/>
<telerik:GridBoundColumn/>
</Columns>
</telerik:GridTableView
</DetailTables>
</telerik:RadGrid>
Which gives a nested grid like this:
Now, what I want is to be able to specify a detail table (those sub tables) per row, programmatically.
(I cannot be sure that the columns for the nested table that comes up when I expand the line fgvbvb will be the same as the columns when expanding the line xcxcv).
I have tried, without luck in the OnDataBound handler of the radgrid (in which I omitted <DetailTables>) to access the data structure for nested tables like this:
protected void OnRadGridDataBound(object sender, EventArgs e)
{
foreach (GridDataItem item in grdActivitiesToCopy.MasterTableView.Items)
{
var dg = item.ChildItem.NestedTableViews[0];
}
}
This will overindex the array NestedTableViews because it is empty. Also, item.ChildItem.NestedTableViews has no setter.
How do I populate each row with a detail table one by one manually?

According to Telerik:
RadGrid does not support mixing declarative grid columns with grid
columns added dynamically at runtime. You should either create all the
columns in the grid programmatically, or else define them all in the
ASPX file. When creating Detail tables, it should be created in the
PageInit event.
Creating a Hierarchical Grid Programmatically:
You should follow these basic steps in order to create hierarchical
RadGrid programmatically in the code-behind (having a data source
control for data content generation):
Create the grid dynamically in the Page_Init handler of the page by
calling its constructor.
Specify the preferred settings for your grid instance through its
properties.
Create columns for the grid dynamically. Keep in mind that you have to
first set their properties and then add them to the
MasterTableView/GridTableView collection (discussed in the first
paragraph of this same topic). Thus, their ViewState will be properly
persisted (as LoadViewState is raised after the Init event of the
page).
Set the proper ParentTableRelations for the GridTableViews (along with
their MasterKeyField and DetailKeyField attributes) and DataKeyNames
for the MasterTableView/GridTableViews in the code-behind of the page.
Assign data sources (through the DataSourceID attribute) for each
table in the grid hierarchy.If you do not want to use declarative
relations, generate the data in the NeedDataSource/DetailTableDataBind
handlers of the grid. On DetailTableDataBind you can determine which
data source should be related to the currently bound GridTableView by
checking its Name/DataSourceID property. Here, the Name property must
have a unique value for each detail table (this value has to be
defined previously by the developer) and the DataSourceID is the ID of
the DataSource control responsible for the corresponding detail table
content generation.
Code Sample:
RadGrid RadGrid1 = new RadGrid();
RadGrid1.DataSourceID = "SqlDataSource1";
RadGrid1.MasterTableView.DataKeyNames = new string[] { "CustomerID" };
RadGrid1.Skin = "Default";
RadGrid1.Width = Unit.Percentage(100);
RadGrid1.PageSize = 15;
RadGrid1.AllowPaging = true;
RadGrid1.AutoGenerateColumns = false;
//Add columns
GridBoundColumn boundColumn;
boundColumn = new GridBoundColumn();
boundColumn.DataField = "CustomerID";
boundColumn.HeaderText = "CustomerID";
RadGrid1.MasterTableView.Columns.Add(boundColumn);
boundColumn = new GridBoundColumn();
boundColumn.DataField = "ContactName";
boundColumn.HeaderText = "Contact Name";
RadGrid1.MasterTableView.Columns.Add(boundColumn);
//Detail table - Orders (II in hierarchy level)
GridTableView tableViewOrders = new GridTableView(RadGrid1);
tableViewOrders.DataSourceID = "SqlDataSource2";
tableViewOrders.DataKeyNames = new string[] { "OrderID" };
GridRelationFields relationFields = new GridRelationFields();
relationFields.MasterKeyField = "CustomerID";
relationFields.DetailKeyField = "CustomerID";
tableViewOrders.ParentTableRelation.Add(relationFields);
RadGrid1.MasterTableView.DetailTables.Add(tableViewOrders);
Please refer to this help article for more details:
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/defining-structure/creating-a-radgrid-programmatically#creating-a-hierarchical-grid-programmatically

First of all , because of the life cicle of a asp page. You can't access to a event on a detail table.
If you need to access detail tables , items etc ..
You need to add an method to the PreRender in the MasterTableView like this:
<MasterTableView DataSourceID="myDataSource"
AllowMultiColumnSorting="True"
DataKeyNames="Key1,Key2,KeyN"
HierarchyDefaultExpanded="True"
OnPreRender="Unnamed_PreRender" >
The method will recursively iterate through the grid.
The way you do it can change depending on your HieararchyLoadMode.
So this is my way to do it, easiest way exist if you are on Client or Serverbind mode.
Traversing and load mode by the telerik doc .
I'm pretty sure you don't want to :
"populate each row with a detail table one by one manually"
You want to have Multiple table at a Sub Level in your grid and display the rigth one programmatically.
And this is can be done in two easy step:
1/. Create every Detail table in your apsx page.
Please refer to this documentation for more information :
Several tables at a level
2/. Handle the display:
protected void Unnamed_PreRender(object sender, EventArgs e)
{
if (!IsPostBack) myControler(MASTERGRID.MasterTableView);
}
private void myControler(GridTableView gridTableView)
{
GridItem[] nestedViewItems = gridTableView.GetItems(GridItemType.NestedView);
foreach (GridNestedViewItem nestedViewItem in nestedViewItems)
{
foreach (GridTableView nestedView in nestedViewItem.NestedTableViews)
{
if (nestedView.Name == "mytable12" && nestedView.Items.Count == 0)
{ HideExpandColumn(nestedView, nestedView.ParentItem["ExpandColumn"]); }
else if (nestedView.Name == "mytable23")
{
if (nestedView.Items.Count == 0)//
HideExpandColumn(nestedView, nestedView.ParentItem["ExpandColumn"]);
else
{ }
}
if (nestedView.HasDetailTables)
{ myControler(nestedView); }
}
}
}
private void HideExpandColumn(GridTableView _GNVI, TableCell _cell)
{
if (_cell.Controls.Count > 0)
{
_cell.Controls[0].Visible = false;
_cell.Text = " ";
}
_GNVI.Visible = false;
}
You can hide a detail table using :
HideExpandColumn(nestedView, nestedView.ParentItem["ExpandColumn"]);
Or you can hide the parent of the detail table you tested using the detail table that is in param of the controler :
HideExpandColumn(gridTableView, nestedView.ParentItem["ExpandColumn"]);
HideExpandColumn will hide the expand control that stay sometimes even if you hide th detail table.
Bonus: If you need to access to a control in a detail table.
You can use this:
public static class ControlExtensions
{
public static Control FindIt(this Control control, string id)
{
if (control == null) return null;
Control ctrl = control.FindControl(id);
if (ctrl == null)
{
foreach (Control child in control.Controls)
{
ctrl = FindIt(child, id);
if (ctrl != null) break;
}
}
return ctrl;
}
}
Calling it in your controler like this :
else if (nestedView.Name == "DetailPV")
{
if (nestedView.Items.Count == 0)
HideExpandColumn(gridTableView, nestedView.ParentItem["ExpandColumn"]);
else
{
RadLabel ctrl = (RadLabel)this.FindIt("RadLabel11");
ctrl.Text += "<b>" + nestedView.Items.Count.ToString() + "</b>";
}

Related

Oracle ADF LOVs value binding to multiple text fileds

I have a use case where I have created a view object that contains 3 values namely LOC_CODE, LOC_DESC, CITY_DESC. Now in my ADF form I would like to display all 3 values in such a way so that user would have a provision to select LOC_CODE From Popup(LOV) and rest two fileds LOC_DESC & CITY_DESC should be changed accordingly. Currently the popup shows all 3 values but when I select the row and click on OK button it only fills the LOC_CODE in 1 textbox.
Below is the scenario of the same:
Got the solution. Just need to add a textbox or drag and drop near respective field and bind it with required binding object. For e.g. in this case LOC_DESC & CITY_DESC is available in my data control as DefLoc & DefCity that contains SQL to fetch respective description value. Now I need to drag and drop DefLoc & DefCity and binding is automatically done or just check binding in value.
you have to add valuechangelistener to location code. set autosubmit true.
now in backing bean use following code:
public void valuechangelistener(ValueChangeEvent valueChangeEvent) {
valueChangeEvent.getComponent().processUpdates(FacesContext.getCurrentInstance());
BindingContext bctx = BindingContext.getCurrent();
BindingContainer bindings = bctx.getCurrentBindingsEntry();
JUCtrlListBinding list = (JUCtrlListBinding)bindings.get("LOC_CODE");
String selectedValue = (String)list.getAttributeValue();
list.getListIterBinding().setCurrentRowWithKeyValue(selectedValue);
Row currRow = list.getListIterBinding().getCurrentRow();
if (currRow != null) {
bndloc_desc.setValue(currRow.getAttribute("LOC_DESC"));
bndcity_desc.setValue(currRow.getAttribute("CITY_DESC"));
}
}
now set partial trigger to both location desc and city desc with id of LOC_CODE.
After doing this you will get your desired result.
update after implementing it.
In my case JDeveloper 12.2.1.3.0
public void valueChangeListener(ValueChangeEvent valueChangeEvent) {
BindingContext bctx = BindingContext.getCurrent();
BindingContainer bindings = bctx.getCurrentBindingsEntry();
JUCtrlListBinding list = (JUCtrlListBinding) bindings.get("YourBindingforLOV");
String selectedValue = (String) valueChangeEvent.getNewValue();
list.getListIterBinding().setCurrentRowWithKeyValue(selectedValue);
Row currRow = list.getListIterBinding().getCurrentRow();
if (currRow != null) {
String s = (String) currRow.getAttribute("YourAttributeName");
}
}

How to count total Local Data rows for Data Driven testing and then perform a function on a particular row?

I'm writing test automation scripts that is based on Data Driven testing for Web Browser test. I'm using Local Data as my data source.
Eg: Local Data table contains 2 rows and 2 columns for Username and Password.
I'm wondering is there is a way to perform a row "Count" function for the Local Data table.
And then,if the row count is two, perform a specific function.
The idea is something like this :
if LocalData.Row = 2 then
//Execute a function
else
//Close Browser
I can't seem to find any resources in the net for this. I'm just being introduced to Telerik so i'm learning as it goes and i'm really hoping you guys can help to give some pointers on this question.
Many many thanks in advance :)
Column and row are two different things.
When accessing the column by the RAD_Grid.MasterTableView.Columns.
You will be able to modify all the properties of a column. Like :
FilterDelay, CurrentFilterFunction, ShowFilterIcon, DataField, UniqueName, Display, Exportable...
foreach (GridColumn column in RAD_Grid.MasterTableView.Columns)
{
if (column is GridBoundColumn)
{
GridBoundColumn boundColumn = column as GridBoundColumn;
boundColumn.CurrentFilterValue = string.Empty;
}
}
To iterate through the row, on the data bound:
protected void Unnamed_DataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
// LOGIC
}
//Total Item Count:
if (e.Item is GridPagerItem)
{
int itemsCount = ((GridPagerItem)e.Item).Paging.DataSourceCount;
}
}
Or
GridItemCollection gridRows = RAD_Grid.Items;
int i;
foreach (GridDataItem data in gridRows)
{
i++;
ItemClass obj = (ItemClass)data.DataItem;
}
As its not really clear what you want I will give you an other way around.
In your grid put a templated Column. I' am pretty sure that's what you are looking for. And if the logic is complexe put it in a function in code behind and simply :
<asp:Label ID="lbl_Exmpl" runat="server"
Text=' <%# MyFunction( Convert.ToInt32(Eval("Mydata")) ) %>' />

Primefaces datatable sort order

I am using primefaces' datatable component to display a list of classes 'Student' which is something like :
class Student {
String firstName
String lastName
....
}
I populate the list form a native query. The datatable component is as follows :
<p:dataTable id="studentList" var="student" rowIndexVar="rowIndex"
value="#{studentBean.studentList}"
rowKey="#{student.firstName}" widgetVar="sList"
sortBy="#{student.firstName}" sortOrder="ASCENDING">
And I have a button which would basically refresh the data in the table. The problem is, when I refresh the data, the sorting order is all lost. How can I retain the sorting order?
The problem is that sorting is only applied just when you click the sorting icon. As a work around you can call some methods in datatable component to, first know what the last "sorted by column" and the you can use the primefaces datatable sorting feature. This will force the datatable to do the sorting whenever you want:
/**
* This code will first find what is the current order and the apply the sorting process to data.
* It is implemented looking at primefaces code and doing exactly the same steps on sorting (like default database sort)
* and decide what is the current order (like in column rendering to decide what is the column arrow style).
*/
protected void refrestTableComponentOrder(DataTable table) {
FacesContext facesContext = FacesContext.getCurrentInstance();
//When view is not created, like on first call when preparing the model, table will not be found
if(table == null){
return;
}
ValueExpression tableSortByVe = table.getValueExpression("sortBy");
String tableSortByExpression = tableSortByVe.getExpressionString();
//Loop on children, that are the columns, to find the one whose order must be applied.
for (UIComponent child : table.getChildren()) {
Column column = (Column)child;
ValueExpression columnSortByVe = column.getValueExpression("sortBy");
if (columnSortByVe != null) {
String columnSortByExpression = columnSortByVe.getExpressionString();
if (tableSortByExpression != null && tableSortByExpression.equals(columnSortByExpression)) {
//Now sort table content
SortFeature sortFeature = new SortFeature();
sortFeature.sort(facesContext, table, tableSortByVe, table.getVar(),
SortOrder.valueOf(table.getSortOrder().toUpperCase(Locale.ENGLISH)), table.getSortFunction());
break;
}
}
}
}
You can find the datatable component anywhere by calling:
FacesContext facesContext = FacesContext.getCurrentInstance();
DataTable table = (DataTable)facesContext.getViewRoot().findComponent(":YOUR_TABLE_CLIENT_ID");

ASPxGridView Group Summary Sorting - It sorts the content inside, not the summary outside

I have done grouping of the grid by giving groupindex to a particular column in aspxgridview.
For example, if I am grouping by means of persons name and the orders details made by that particular person would come in the detailed content when the arrow is clicked to view the content.
When I click on the header fields to sort, it is sorting the data inside the groupContent but it is not used for sorting the data of groupsummary
I am showing all the totals as a part of group summary besides the person's name.
For example if you see in the below link:
https://demos.devexpress.com/ASPxGridViewDemos/Summary/GroupSortBySummary.aspx
If you sort by company name, the content would be sorted, but the summary showing the country and sum has no means to get sorted at outside level.
Please do suggest me options to work out this problem.
Thanks.
Here is workaround, based on this example.
The main idea is to create summary item which shows the minimum or maximum value of Country column inside City group and sort City group by this summary values. For this BeforeColumnSortingGrouping event is used to change the sorting behavior.
Here is example:
<dx:ASPxGridView ...
OnBeforeColumnSortingGrouping="gridCustomers_BeforeColumnSortingGrouping">
private void SortByCountry()
{
gridCustomers.GroupSummary.Clear();
gridCustomers.GroupSummarySortInfo.Clear();
var sortOrder = gridCustomers.DataColumns["Country"].SortOrder;
SummaryItemType summaryType = SummaryItemType.None;
switch (sortOrder)
{
case ColumnSortOrder.None:
return;
break;
case ColumnSortOrder.Ascending:
summaryType = SummaryItemType.Min;
break;
case ColumnSortOrder.Descending:
summaryType = SummaryItemType.Max;
break;
}
var groupSummary = new ASPxSummaryItem("Country", summaryType);
gridCustomers.GroupSummary.Add(groupSummary);
var sortInfo = new ASPxGroupSummarySortInfo();
sortInfo.SortOrder = sortOrder;
sortInfo.SummaryItem = groupSummary;
sortInfo.GroupColumn = "City";
gridCustomers.GroupSummarySortInfo.AddRange(sortInfo);
}
protected void Page_Load(object sender, EventArgs e)
{
SortByCountry();
}
protected void gridCustomers_BeforeColumnSortingGrouping(object sender, ASPxGridViewBeforeColumnGroupingSortingEventArgs e)
{
SortByCountry();
}
When you group by a column devexpress automatically uses that column to sort. Without sorting the data the grouping is not possible. To overcome this issue we have sorted the datasource itself then applied that datasource to the grid.

What's problem on linq databinding

<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
KeyFieldName="CategoryID">
<SettingsEditing Mode="Inline" />
<Columns>
<dx:GridViewCommandColumn VisibleIndex="0">
<EditButton Visible="True"></EditButton>
<NewButton Visible="True"></NewButton>
<DeleteButton Visible="True"></DeleteButton>
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn Caption="CategoryID" FieldName="CategoryID"
VisibleIndex="1">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="CategoryName" FieldName="CategoryName"
VisibleIndex="2">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Description" FieldName="Description"
VisibleIndex="3">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
C# syntax:
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories
.Select(p => new { p.CategoryID, p.CategoryName, p.Description}));
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
If you run the code, you get a gridview which is filled by NorthWind Categories table. If you click on command button of grid whose are on left side, you get insert/update field, but you have not access to give input. They are gone to read only mode.
If I replace the above C# syntax with below
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories);
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
then it works fine. Now you can work with command button with out facing any problem.
I want to know what the problem is, why the first syntax does not work. Maybe you say
Anonymous types are class types that consist of one or more public read-only properties. But when you need to join more than one table and need to select several fields not all than what you do. Hope you not say linq is fail to do that or Don't think it is possible. Hope there must be any technique or else something to bind control with Anonymous type. Plz show some syntax .
The problem is that the result set is collection of Anonymous type as you supposed and the grid doesn't know how to treat it. What you have to do is to use RowInserting and RowUpdating events of the grid.
Here is an example of how I use DevExpress grid with NHibernate:
protected void gridAgentGroups_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
ASPxGridView currentGrid = sender as ASPxGridView;
var currentAgentGroup = new AgentGroup();
if (e.NewValues.Contains("Name"))
{
var newValue = (string)e.NewValues["Name"];
currentAgentGroup.Name = newValue;
}
if (e.NewValues.Contains("PhysicalAddress"))
{
var newValue = (string)e.NewValues["PhysicalAddress"];
currentAgentGroup.PhysicalAddress = newValue;
}
AgentGroupsDataAccess.SaveAgentGroup(currentAgentGroup);
e.Cancel = true;
currentGrid.CancelEdit();
currentGrid.DataBind();
}
protected void gridAgentGroups_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
ASPxGridView currentGrid = sender as ASPxGridView;
int currentAgentGroupId = (int)((AgentGroup)currentGrid.GetRow(currentGrid.EditingRowVisibleIndex)).Id;
var currentAgentGroup = AgentGroups.Where(ag => ag.Id == currentAgentGroupId).FirstOrDefault();
if (e.NewValues.Contains("Name"))
{
var newValue = (string)e.NewValues["Name"];
currentAgentGroup.Name = newValue;
}
if (e.NewValues.Contains("PhysicalAddress"))
{
var newValue = (string)e.NewValues["PhysicalAddress"];
currentAgentGroup.PhysicalAddress = newValue;
}
AgentGroupsDataAccess.SaveAgentGroup(currentAgentGroup);
e.Cancel = true;
currentGrid.CancelEdit();
currentGrid.DataBind();
}
I hope this will help.
Just a wild guess - you're binding your data to the grid using field names - yet, your anonymous type doesn't really have any field names.
Does it make any difference if you try this code:
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories
.Select(p => new { CategoryID = p.CategoryID,
CategoryName = p.CategoryName,
Description = p.Description}));
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
Again - I don't have the means to test this right now, it's just a gut feeling..... try it - does that help at all??
You actually can bind with anonymous type as you see the already filled rows. But: the grid itself cannot know how you build the query and what to add additionally to the visible columns (if there are valid default values).
As you use Developer Express' grid you have the option to provide your own update / edit form and handle everything needed on your own.

Resources