Binding IEnumerable<anonymous object> to DataGrid in WPF - wpfdatagrid

I need merely a readonly display of Linq data; no requirement to observe changes. Here's the Linq:
string ZIPCODEFIELDNAME="zip5";
DataTable DATA = (detailedQueryResult as DataTable);
IEnumerable<object> ZIPCODE_SUMMARY;
ZIPCODE_SUMMARY = from z in DATA.AsEnumerable()
group z by z.Field<string>(ZIPCODEFIELDNAME) into g
let list = g.ToList()
select new
{
zip = g.Key,
eecount = list.Count(),
// possible additional aggregate columns here
};
I am able to bind this IEnumerable<anonymous object> to a Telerik RadGridView in code-behind simply by doing this:
myRadGridView.ItemsSource = ZIPCODE_SUMMARY.ToList();
that is, without having to declare a binding in XAML or having to define any columns. How would that be accomplished using the WPF DataGrid that ships with Visual Studio? It displays only row separators when I use the identical approach. So it knows about the items in the list, just not how to fetch the columns.
I am trying to write some quick-and-dirty utilities to import a gazillion CSV files where no two of them have the same structure or same field names, and the fewer lines of setup code the better.
P.S. I am just getting into WPF and Linq, so please set ReplyToNovice=true :-)

Did you remember to set AutoGenerateColumns=true on the datagrid? If yes, try binding to an ICollectionView instead.
UPDATE:
Thats weird, the code below works fine for me. One thing though, you may have to set the datacontext of the datagrid to {Binding}, this will bind to the whole object.
public MainWindow()
{
InitializeComponent();
dgZips.ItemsSource = GetFakeZips();
}
public dynamic GetFakeZips()
{
return Enumerable.Range(1500, 10).Select(i => new { Zip = i, Count = i / 4 });
}
Xaml:
<DataGrid x:Name="dgZips" AutoGenerateColumns="True" />

Related

Retain Sort Order of Datagrid View after Updating SQL Adapter

As the title says, I am looking for a way to retain the sort order of my DataGridView after refreshing the data from SQL.
If I sort any of my columns, as soon as the data is refreshed, the columns are no longer sorted and the selected row I had is no longer selected.
Is there an easy solution that would be something along the lines of:
Dim NewSort as Something
SortOrder = DataGridView1
DataGridView1.Refresh
DataGridView1.SortOrder = NewSort
I know the above code is hypothetical but I would be pleased with any solution or to be pointed in the right direction. Google and Bing have not produced helpful resources.
I assume you have a sort, you do a database refresh and your sort is gone. I've encountered this before. I created an inherited grid to handle this, but there's the general idea.
Assuming you are binding to a DataView, consider this.
' Get the Sort
string currentSort = "";
if ( grid.DataSource != null )
currentSort = ((DataView) grid.DataSource).Sort
' Reset the Data Source
grid.DataSource = yournewsource of data ' Better Be a Data View
' Recall the Sort
((DataView) grid.DataSource).Sort = currentSort
One thing I did was had an inherited grid where the data the DataSource Get property was overwritten to have this, and used the inherited grid throughout the application, rather than having to put this code everywhere. It's easy enough to change to an inherited grid if you are comfortable going into the Designer file and editing.
public class MyDataGridView : System.Windows.Forms.DataGridView
{
public object DataSource
{
get
{
return base.DataSource;
}
set
{
string currentSort = "";
if (!(base.DataSource == null))
currentSort = ((DataView)base.DataSource).Sort;
base.DataSource = value;
((DataView)base.DataSource).Sort = currentSort;
}
}
}

Add parameter to Telerik report from codebehind using mvc 4

I am very new to Telerik Reporting as well as MVC. I am using Telerik Reporting Q1 2013 and MVC 4. I want to pass some info as parameter to report. I tried by sending parameter from code behind of report, but no use. It showing all record.
What I have done is
public partial class ImmunizationRpt : Telerik.Reporting.Report
{
public ImmunizationRpt()
{
InitializeComponent();
Telerik.Reporting.ReportParameter param = new ReportParameter();
param.Name = "PatientKey";
param.Type = ReportParameterType.Integer;
param.AllowBlank = false;
param.AllowNull = false;
param.Value = 1;
param.Visible = true;
this.Report.ReportParameters.Add(param);
//this.Report.ReportParameters.Add("PatientKey",ReportParameterType.Integer,1);
}
}
If the parameter is already defined in the report, you can access it through the collection.
this.Report.ReportParameters["PatientKey"].Value = 1;
thank you for reply! i have achived this as
my report was showing all records, because i hadn't set the report to filter the records based on the parameter value. To achieve that, first we need to add the new parameter from the code behind (as i did) and then we need to add a new filter as shown in the following code:
Telerik.Reporting.Filter filter1 = new Telerik.Reporting.Filter();
filter1.Expression = "=Fields.PatientKey";
filter1.Operator = Telerik.Reporting.FilterOperator.Equal;
filter1.Value = "=Parameters.PatientKey.Value";
report.Filters.Add(filter1);

How to customize the labels of an Infragistics Ultrachart?

I am trying to customize the series labels of the X axis of a linear ultrachart using vb.net.
I looked into the documentation from Infragistics and found that I could use this code:
UltraChart.Axis.Y.Labels.SeriesLabels.FormatString = "<Item_Label>"
A description of the types of labels available can be seen here.
However, I'm not getting the result I expected. I get "Row#1" and I want to get only the "1".
I've tried the approach used in the first reply of this post in Infragistics forums, which consists of using an hashtable with the customized labels. The code used there is the following (in C#):
Hashtable labelHash = new Hashtable();
labelHash.Add("CUSTOM", new MyLabelRenderer());
ultraChart1.LabelHash = labelHash;
xAxis.Labels.ItemFormatString = "<CUSTOM>";
public class MyLabelRenderer : IRenderLabel
{
public string ToString(Hashtable context)
{
string label = (string)context["ITEM_LABEL"];
int row = (int)context["DATA_ROW"];
int col = (int)context["DATA_COLUMN"];
//use row, col, current label's text or other info inside the context to get the axis label.
//the string returned here will replace the current label.
return label;
}
}
This approach didn't work either.
I am using Infragistics NetAdvantage 2011.1.
Anyone has any idea how to customize these labels in order to obtain the number after "Row#"?
There are different approaches to solve this task. One possible solution could be if you are using FillSceneGraph event. By this way you could get your TEXT primitives and modify it. For example:
private void ultraChart1_FillSceneGraph(object sender, Infragistics.UltraChart.Shared.Events.FillSceneGraphEventArgs e)
{
foreach (Primitive pr in e.SceneGraph)
{
if (pr is Text &&((Text)pr).labelStyle.Orientation == TextOrientation.VerticalLeftFacing )
{
pr.PE.Fill = Color.Red;
((Text)pr).SetTextString("My custom labels");
}
}
}
OK. I`ll try to explain more deeply about FormatString property.
When you are using this property, you could determinate which information to be shown (for example: Items values or Data Values or Series Values). Of course there are option to use your custom FormatString.
For example:
axisX2.Labels.ItemFormat=AxisItemLabelFormat.Custom;
axisX2.Labels.ItemFormatString ="";
In this case we have labels which represent Date on your X axis, so if you are using these two properties, you are able to determinate the Date format (for example dd/MM/yyyy or MM/ddd/yy). In your scenario you have string values on your X axis. If you are not able to modify these strings values at lower level (for example in your database, through TableAdapters SQL query, DataSet, i.e. before to set your DataSource to our UltraChart), then you could use FillSceneGraph event and modify your Text primitives. More details about this event you could find at http://help.infragistics.com/Help/NetAdvantage/WinForms/2013.1/CLR4.0/html/Chart_Modify_Scene_Graph_Using_FillSceneGraph_Event.html If you need a sample or additional assistance, please do not hesitate to create a new forum thread in our web site - http://www.infragistics.com/community/forums/
I`ll be glad to help you.

How to add one more properties in current class at runtime using C#

I have some properties in my viewmodel. At runtime I need to add one more property into that viewmodel.
For example:
var avm= new AnalysisViewModel();
foreach (var grades in gradeList)
{
avm = new AnalysisViewModel
{
InfractionAverage = searchResult.Where(x=>x.GradeId == grades),
//Here i want to add one move property and want to assign value for my list.
};
}
Please guide me how to achieve this requirement
Hmm try with PropertyBuilder. http://msdn.microsoft.com/en-us/library/system.reflection.emit.propertybuilder.aspx

Using the return type IQueryable<TABLE_1>

I am new to silverlight, many posts indicate using observablecollection is the best.
Domainservice1 returns IQUERYABLE type.
How to work with this return type in
silverlight side?
How to convert/cast the data returned
to observable collection?
The DomainServices1.cs
public IQueryable<TABLE_1> GetTABLE_1()
{
return this.ObjectContext.TABLE_1;
}
*The HOME.XAML.CS***
public Home()
{
InitializeComponent();
this.Title = ApplicationStrings.HomePageTitle;
Web.DomainService1 dservice = new Web.DomainService1();
EntityQuery<Web.TABLE_1> query=new EntityQuery<Web.TABLE_1>();
query = dservice.GetTABLE_1Query();
//Convert result to ObservableCollection
//bind the grid ITEM SOURCE
}
The IQueryable does not return results until you enumerate the collection. so for instance if you wanted to limit the results of that dservice.getTable_1Query with a .where() you could...
to get the object into an observable collection you .tolist the query like this
observablecollection<Table1> t=new observablecollection<Table1>(query.ToList());
I actually think there is a little more that you have to do(a loadoperation is how I do mine)
I am in the learning stages of the linq dynamic, but from other applications that i have had to convert returned results to an observable collection; that is how i did it. I actually wrote an exension so that I could .ToObservableCollection