DynamicDataDisplay chart horizontal string axis - c#

I need to draw some charts using DynamicDataDisplay3. Everything works fine, except I can't find a way to change X axis to strings instead of dates or integers. This is how I tried to do it but I get only 1 value on X axis:
int i = 0;
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
i++;
Analyze build = new Analyze();
build.id = i;
build.build = Convert.ToString(reader[0]);
builds.Add(build);
n1.Add(Convert.ToInt32(reader[1]));
}
}
var datesDataSource = new EnumerableDataSource<Analyze>(builds);
datesDataSource.SetXMapping(x => x.id);
var numberOpenDataSource = new EnumerableDataSource<int>(n1);
numberOpenDataSource.SetYMapping(y => y);
CompositeDataSource compositeDataSource1 = new CompositeDataSource(datesDataSource, numberOpenDataSource);
chBuild.AddLineGraph(compositeDataSource1, new Pen(Brushes.Blue, 2), new CirclePointMarker { Size = 6, Fill = Brushes.Blue }, new PenDescription(Convert.ToString(cmbBuildVertical.SelectedItem)));
chBuild.Viewport.FitToView();

I made my own LabelProvider to handle something similar to this. I wanted to override my DateTime labels into integers, to represent something different. In your case you could use something like this :
public class StringLabelProvider : NumericLabelProviderBase {
private List<String> m_Labels;
public List<String> Labels {
get { return m_Labels; }
set { m_Labels = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="ToStringLabelProvider"/> class.
/// </summary>
public StringLabelProvider(List<String> labels) {
Labels = labels;
}
public override UIElement[] CreateLabels(ITicksInfo<double> ticksInfo) {
var ticks = ticksInfo.Ticks;
Init(ticks);
UIElement[] res = new UIElement[ticks.Length];
LabelTickInfo<double> tickInfo = new LabelTickInfo<double> { Info = ticksInfo.Info };
for (int i = 0; i < res.Length; i++) {
tickInfo.Tick = ticks[i];
tickInfo.Index = i;
string labelText = "";
labelText = Labels[Convert.ToInt32(tickInfo.Tick)];
TextBlock label = (TextBlock)GetResourceFromPool();
if (label == null) {
label = new TextBlock();
}
label.Text = labelText;
res[i] = label;
ApplyCustomView(tickInfo, label);
}
return res;
}
}
You can construct your list of ticks, and send it to the LabelProvider you create. Like this :
StringLabelProvider labelProvider = new StringLabelProvider(yourLabelList);
yourAxis.LabelProvider = labelProvider;

Related

Is there a way to add descriptive text beside each data point in BarChart BarChartSeries using OpenXML(C#) for PPT?

I am able to get the 0 as value. However I want to set a descriptive text like B does not have any data and similar is the case for D here in the chart.
I want to have text whenever a company does not have any value which is 0 in this case. This can happen for multiple companies so how can I automate this?
I am using this to put category data-Sample code
DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData categoryAxisData1 = new DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData();
C.StringReference stringReference2 = new C.StringReference();
C.Formula formula2 = new C.Formula
{
Text = "Sheet1!$A$2:$A$7"
};
C.StringCache stringCache2 = new C.StringCache();
C.PointCount pointCount2 = new C.PointCount() { Val = Convert.ToUInt32(companies.Count) };
stringCache2.Append(pointCount2);
int count = 0;
for (int i = companies.Count-1; i >= 0 ; i--)
{
C.StringPoint stringPoint = new C.StringPoint() { Index = Convert.ToUInt32(count) };
C.NumericValue numericValue = new C.NumericValue
{
Text = companies[i].CompanyName
};
stringPoint.Append(numericValue);
stringCache2.Append(stringPoint);
count++;
}
stringReference2.Append(formula2);
stringReference2.Append(stringCache2);
categoryAxisData1.Append(stringReference2);
Sample code for value on barchart-
C.Values values1 = new C.Values();
C.NumberReference numberReference1 = new C.NumberReference();
C.Formula formula3 = new C.Formula
{
Text = "Sheet1!$B$2:$B$7"
};
C.NumberingCache numberingCache1 = new C.NumberingCache();
C.FormatCode formatCode1 = new C.FormatCode
{
Text = "General"
};
numberingCache1.Append(formatCode1);
C.PointCount pointCount3 = new C.PointCount() { Val = Convert.ToUInt32(companies.Count) };
numberingCache1.Append(pointCount3);
for (int i = 0; i < companies.Count; i++)
{
C.NumericPoint numericPoint = new C.NumericPoint() { Index = Convert.ToUInt32(i) };
//C.NumericValue numericValue = new C.NumericValue
//{
// Text = (sliderValueForComapnies[i] > 0) ? sliderValueForComapnies[i].ToString() : "Data not avaialble",
//};
C.NumericValue numericValue = new C.NumericValue();
if (sliderValueForComapnies[i] > 0)
{
numericValue.Text = sliderValueForComapnies[i].ToString();
}
//else
//{
// this area will have the companies with 0 as value so what can I do here to add text?
//}
numericPoint.Append(numericValue);
numberingCache1.Append(numericPoint);
}
numberReference1.Append(formula3);
numberReference1.Append(numberingCache1);
values1.Append(numberReference1);

MVVM with dynamic the Michrochart-NugetPackage doesn't work

I want to add a dynamic micro chart to my application but it doesn't work. After a call from a method a value gets added and it makes a completely new micro chart for my chart to have the new values, but the change isn't visible in the app. So the old Values stayed and there is no new one. Thanks for helping me.
WeightList = new List<float>();
WeightList.Add(0);
WeightList.Add((float)74.3);
entries = new ChartEntry[30];
SyncArray();
private void SyncArray()
{
if (WeightList.Count != entries.Length)
{
entries = new ChartEntry[WeightList.Count];
}
for (int i = 0; i <= WeightList.Count - 1; i++)
{
if (i == WeightList.Count - 1 || i == 0)
{
entries[i] = new ChartEntry(WeightList[i]) { Label = "" + i, ValueLabel = "" + WeightList[i] };
}
else
{
entries[i] = new ChartEntry(WeightList[i]) { Label = "" + i };
}
}
chart = new LineChart() { Entries = entries, BackgroundColor = SKColors.Transparent };
Chart = chart;
}
public LineChart Chart
{
get => chart;
set => SetProperty(ref chart, value);
}
public float Weight
{
get => weight;
set
{
weight = value;
WeightList.Add(weight);
SyncArray();
}
}
Credits: #Jason
What to change:
private void SyncArray()
{
if (WeightList.Count != entries.Length)
{
entries = new ChartEntry[WeightList.Count];
}
for (int i = 0; i <= WeightList.Count - 1; i++)
{
if (i == WeightList.Count - 1 || i == 0)
{
entries[i] = new ChartEntry(WeightList[i]) { Label = "" + i, ValueLabel = "" + WeightList[i] };
}
else
{
entries[i] = new ChartEntry(WeightList[i]) { Label = "" + i };
}
}
Chart = new LineChart() { Entries = entries, BackgroundColor = SKColors.Transparent };
}

How to check if checkbox is selected?

I have little issue with checkbox added programmatically. I don't know how to check which checkbox are selected, when I hit "Send Button".
layout.RemoveAllViewsInLayout();
CheckBox _Options = new CheckBox(Activity);
ScrollView _Scroll = new ScrollView(Activity);
_Scroll.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
LinearLayout _LScroll = new LinearLayout(Activity);
_LScroll.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
_LScroll.Orientation = Orientation.Vertical;
_LScroll.SetGravity(GravityFlags.CenterHorizontal);
//_Scroll.AddView(_LScroll);
Button _Send = new Button(Activity);
_Send.Text = "Wyƛlij";
_Send.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
for (int i = 0; i < _Item.options.Length; i++)
{
_Options.Text = _Item.options[i];
_Options.Id = i;
_Options.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
_LScroll.AddView(_Options);
}
_Send.Click += delegate
{
_MultiAnswer._QuestionId = _Item.id;
for(int i = 0; i < _Item.options.Length; i++)
{
if (_Options.Selected == true)
{
_MultiAnswer._AnwserOptionIds.SetValue(i + 1, i);
}
}
output = JsonConvert.SerializeObject(_MultiAnswer);
SendJson(_Url, DataCache._Login, output);
SetLayout(layout, btn);
};
_Scroll.AddView(_LScroll);
layout.AddView(_Scroll);
layout.AddView(_Send);
I'll try to work on ID of checkbox, but I really don't know how to do it. I was thinking on method, which give me code which create checkbox, but still don't know how to check if checkbox is selected.
I understand that you've many checkbox controls. So add them to a list as follows:
List<Checkbox> checkboxes = new List<Checkbox>
{
chk1, chk2, chk3
};
When you want to know which ones are checked, you'll do this:
IEnumerable<Checkbox> checkedCheckboxes = checkboxes.Where(chk => chk.Checked);
This is a quick and dirty sample on how to generate dynamic cheboxes and retreive their state :
public class MainActivity : Activity
{
public class MyItem
{
public string[] options { get; set; }
public int id { get; set; }
}
public class MyMultiAnswer
{
public int _QuestionId { get; set; }
}
private List<CheckBox> _chkList = new List<CheckBox>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
var _Item = new MyItem() { options =new string [] { "aaa", "bbb", "ccc" }, id=0 };
var _MultiAnswer = new MyMultiAnswer() { _QuestionId = 0 };
ScrollView _Scroll = new ScrollView(this);
_Scroll.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
LinearLayout _LScroll = new LinearLayout(this);
_LScroll.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
_LScroll.Orientation = Orientation.Vertical;
_LScroll.SetGravity(GravityFlags.CenterHorizontal);
TextView txView = new TextView(this);
//_Scroll.AddView(_LScroll);
Button _Send = new Button(this);
_Send.Text = "test";
_Send.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
for (int i = 0; i < _Item.options.Length; i++)
{
CheckBox _Options = new CheckBox(this);
_chkList.Add(_Options);
_Options.Text = _Item.options[i];
_Options.Id = i;
_Options.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
_LScroll.AddView(_Options);
}
_Send.Click += delegate
{
_MultiAnswer._QuestionId = _Item.id;
string strChkIds = "";
foreach (var chk in _chkList.Where(c => c.Checked))
{
//_MultiAnswer._AnwserOptionIds.SetValue(_Options.Id + 1, _Options.Id);
//do something
strChkIds += " - " + chk.Id;
}
// or
for (int i = 0; i < _Item.options.Length; i++)
{
if (_chkList[i].Checked == true)
{
//_MultiAnswer._AnwserOptionIds.SetValue(i + 1, i);
//do something
}
}
//output = JsonConvert.SerializeObject(_MultiAnswer);
//SendJson(_Url, DataCache._Login, output);
//SetLayout(layout, btn);
txView.Text = "selected ids " + strChkIds;
};
_Scroll.AddView(_LScroll);
_LScroll.AddView(_Send);
_LScroll.AddView(txView);
// Set our view from the "main" layout resource
SetContentView(_Scroll);
}
}
This is a sample about how you can achieve this in a minimum effort.

xamGeographicMap shapes from SQL server data

Using the Infragistics xamGeographicMap control, trying to add shapes from SQL server geometry data.
The data is valid; a select in SSMS shows the shapes properly
Points show properly when querying SP_GEOMETRY (see sample) -- so GeographicSymbolSeries works, and the shape columns contain actual data
GeographicShapeSeries does not work
GeographicPolyLine does not work
So this works:
var majorCitySeries = new GeographicSymbolSeries
{
ItemsSource = data.cities,
LatitudeMemberPath = "SP_GEOMETRY.YCoordinate",
LongitudeMemberPath = "SP_GEOMETRY.XCoordinate"
};
GeoMap.Series.Add(majorCitySeries);
But these show nothing:
var countySeries = new GeographicShapeSeries
{
ItemsSource = data.counties,
ShapeMemberPath = "SP_GEOMETRY"
};
GeoMap.Series.Add(countySeries);
var br = new GeographicPolylineSeries
{
ItemsSource = data.rivers,
ShapeMemberPath = "SP_GEOMETRY"
};
GeoMap.Series.Add(br);
Do I need to add a converter? The samples, they tell nothing. What gives?
Ok, fixed it. Here's a semi-generic converter:
public static class SqlGeometryToShapeConverter
{
public static ShapefileConverter Create<T>(IEnumerable<T> items,
Func<T, DbGeometry> geoFunc,
Func<T, string> nameFunc)
where T : class
{
var converter = new ShapefileConverter();
foreach (var item in items)
{
var rec = new ShapefileRecord();
var points = new List<Point>();
var geometry = geoFunc(item);
Debug.Assert(geometry.PointCount != null, "geometry.PointCount != null");
// Points are 1 based in DbGeometry
var pointCount = geometry.PointCount;
for (var pointIndex = 1; pointIndex <= pointCount; pointIndex++)
{
var point = geometry.PointAt(pointIndex);
Debug.Assert(point.XCoordinate != null, "point.XCoordinate != null");
Debug.Assert(point.YCoordinate != null, "point.YCoordinate != null");
points.Add(new Point(point.XCoordinate.Value, point.YCoordinate.Value));
}
rec.Fields = new ShapefileRecordFields { { "Name", nameFunc(item) } };
rec.Points = new List<List<Point>> { points };
converter.Add(rec);
}
return converter;
}
}
Use it like this:
var countySeries = new GeographicShapeSeries
{
ItemsSource = SqlGeometryToShapeConverter.Create(data.counties, x => x.SP_GEOMETRY, x => x.County_Name),
ShapeMemberPath = "Points"
};
GeoMap.Series.Add(countySeries);
This was a good start for me, but I was running into some issues. Here's my perhaps less elegant approach. Compared to the default Infragistics background, the map is slightly off. Something might be off with my loading of my data in SQL server.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Windows;
using Infragistics.Controls.Maps;
using Microsoft.SqlServer.Types;
namespace TestMVVMLightProject.Model
{
public class SqlGeometryToShapeConverter : ObservableCollection<ShapefileRecord>
{
public SqlGeometryToShapeConverter()
{
//connect
//load sql
//go thorugh points
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "RefDB_91_DistToCoast";
builder.IntegratedSecurity = true;
SqlConnection conn = new SqlConnection(builder.ConnectionString);
conn.Open();
string sql = "SELECT huc_2, geom FROM Polygon2";
using (SqlCommand oCmd = new SqlCommand(sql, conn))
{
oCmd.CommandTimeout = 3000;
using (SqlDataReader oDr = oCmd.ExecuteReader())
{
int ordGeom = oDr.GetOrdinal("geom");
int ordHucZone = oDr.GetOrdinal("huc_2");
double minX = double.MaxValue;
double minY = double.MaxValue;
double maxX = double.MinValue;
double maxY = double.MinValue;
while (oDr.Read())
{
var rec = new ShapefileRecord();
rec.Points = new List<List<Point>>();
SqlGeography coast = (SqlGeography)oDr.GetValue(ordGeom);
int numPolygons = (int)coast.STNumGeometries();
string hucZone = oDr.GetString(ordHucZone);
int hucInt = int.Parse(hucZone);
for (int geomIndex = 1; geomIndex <= coast.STNumGeometries(); geomIndex++)
{
SqlGeography polygon = coast.STGeometryN(geomIndex);
var points = new List<Point>();
for (int verticeIndex = 1; verticeIndex <= polygon.STNumPoints(); verticeIndex++)
{
points.Add(new Point(polygon.STPointN(verticeIndex).Long.Value, polygon.STPointN(verticeIndex).Lat.Value));
if (hucInt < 19)
{
minX = minX < polygon.STPointN(verticeIndex).Long.Value ? minX : polygon.STPointN(verticeIndex).Long.Value;
minY = minY < polygon.STPointN(verticeIndex).Lat.Value ? minY : polygon.STPointN(verticeIndex).Lat.Value;
maxX = maxX > polygon.STPointN(verticeIndex).Long.Value ? maxX : polygon.STPointN(verticeIndex).Long.Value;
maxY = maxY > polygon.STPointN(verticeIndex).Lat.Value ? maxY : polygon.STPointN(verticeIndex).Lat.Value;
}
}
rec.Points.Add(points);
}
rec.Fields = new ShapefileRecordFields { { "HUC_2", hucZone.ToString() } };
this.Add(rec);
}
worldRect = new Rect(new Point(minX, minY), new Point(maxX, maxY));
}
}
conn.Close();
}
private Rect worldRect;
public Rect WorldRect
{
get
{
return worldRect;
}
}
}
}
I called this from my view model (I'm using MVVM Light). This was the code in my view model.
public MainViewModel()
{
mapData = new SqlGeometryToShapeConverter();
}
private SqlGeometryToShapeConverter mapData;
public SqlGeometryToShapeConverter MapData
{
get
{
return mapData;
}
set
{
Set(() => MapData, ref mapData, value);
}
}
This is a snippet from my View
<ig:XamGeographicMap Zoomable="True"
Height="400"
WorldRect="{Binding MapData.WorldRect}">
<ig:XamGeographicMap.Series>
<ig:GeographicShapeSeries ItemsSource="{Binding MapData}"
ShapeMemberPath="Points"
ShapeStyleSelector="{StaticResource shapeStyleSelector}"
MarkerCollisionAvoidance="Fade">
<!-- custom marker with bindings to data loaded from database file (DBF) -->
<ig:GeographicShapeSeries.MarkerTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=Item.Fields[HUC_2]}"
Foreground="#FF333333"
FontWeight="Bold"
Margin="1 1 0 0" />
</Grid>
</DataTemplate>
</ig:GeographicShapeSeries.MarkerTemplate>
</ig:GeographicShapeSeries>
</ig:XamGeographicMap.Series>
</ig:XamGeographicMap>

how to display icon in a cell of a grid view c#

I want to Display an icon in the particular cell.
I am using this code. I have commented where i want to display the icon:
string lastScripDate = this.GetLastScripDate(sFolderPath, pb);
string sQuery = "select * from database";
DataTable table = new DataTable();
table = this.Retrieve_Data(sQuery, "database");
pb.Maximum = table.Rows.Count;
pb.Value = 0;
double num = 0.0;
double num2 = 0.0;
double num3 = 0.0;
double num4 = 0.0;
if (table.Rows.Count > 0)
{
for (int i = 0; i < table.Rows.Count; i++)
{
Application.DoEvents();
dgv.Rows.Add();
dgv.Rows[i].Cells["Sname"].Value = table.Rows[i]["Symbol"].ToString();
dgv.Rows[i].Cells["clsprice"].Value = table.Rows[i]["SCRIP"].ToString();
string str3 = table.Rows[i]["TradeType"].ToString();
dgv.Rows[i].Cells["trd"].Value = str3;
string str4 = str3;
if (str4 != null)
{
if (!(str4 == "p"))
{
if (str4 == "q")
{
goto Label_01DD;
}
}
else
{
dgv.Rows[i].Cells["trd"].Style.ForeColor = Color.Green;///////I Want to Display Icon in this Cell(Up.Ico)
}
}
goto Label_020B;
Label_01DD:
dgv.Rows[i].Cells["Trade"].Style.ForeColor = Color.Red;///////////////An Want to Display Icon in this Cell also(Down.Ico
Label_020B:
dgv.Rows[i].Cells["date"].Value = table.Rows[i]["TDate"].ToString();
num = Convert.ToDouble(table.Rows[i]["CPrice"]);
dgv.Rows[i].Cells["tp"].Value = string.Format("{0:0.00}", num);
num2 = Convert.ToDouble(table.Rows[i]["Price"]);
dgv.Rows[i].Cells["tp"].Value = string.Format("{0:0.00}", num2);
num3 = Convert.ToDouble(table.Rows[i]["Loss"]);
dgv.Rows[i].Cells["sl"].Value = string.Format("{0:0.00}", num3);
try
{
num4 = Convert.ToDouble(table.Rows[i]["Ratio"]);
dgv.Rows[i].Cells["Ratio"].Value = string.Format("{0:0.00}", num4);
}
catch
{ }
pb.Value++;
}
if (pb.Value == pb.Maximum)
{
pb.Value = pb.Minimum;
}
return true;
}
return false;
One way to acheive this would be to add DataGridViewImageColumn and then set icon to that cell. Here is a sample
dataGridView1.Columns.Add(new DataGridViewImageColumn());
dataGridView1.Rows.Add(2);
DataGridViewImageCell cell = (DataGridViewImageCell)dataGridView1.Rows[0].Cells[0];
Icon ic = new Icon("icon.ico");
cell.Value = ic;
1 - create some icons inside a property class
Example
public static class EIcons
{
/// <summary>
/// NULL
/// </summary>
public static readonly Icon NOICON = new Icon("Icon/null.ico");
/// <summary>
/// NEW
/// </summary>
public static readonly Icon NEW = new Icon("Icon/new.ico");
}
2 - Create a property for your datagrid, that contains strings, or int, and also ICONS objects.
The constructor must always initialize your icon to something consistent.
public class GridProperty01
{
/// <summary>
/// CONSTRUCTOR - factory initialization
/// </summary>
public GridProperty01()
{
ID = 0;
NewValue = string.Empty;
Alert = EIcons.NOICON; // solid icon initialization. Create transparent icon if you wish...
}
public int ID { get; set; }
public string NewValue { get; set; }
public Icon Alert { get; set; } // for icon
}
3 - Create a list of data and assign to your icon property the icon you need. At last bind the list to your datagrid, and refresh.
All this code must be put inside a button of SEARCH for example, or inside a method that update the gridview..
// GET - data for datagridview
List<GridProperty01> tempList = new List<GridProperty01>();
for (int jj = 0; jj < 3; ++jj) {
// INIT
GridProperty01 tempObj = new GridProperty01();
// GET - data
tempObj.ID = jj; // your code...
tempObj.NewValue = "xxx"; // your code...
tempObj.Alert = EIcons.NEW; // an icon...
// SET - insert row to list
tempList.Add(tempObj);
}
// SET - assign list to your gridview
dataGridView01.DataSource = tempList;
// SET - refresh
dataGridView01.Update();
dataGridView01.Refresh();
I suppose that's enough.
In addition, if you plan to SORT the Icon column when the column header has been clicked, create an Icon Text property, that contains different "text" accordingly to your Icon property. At the sort use this string to sort the rows of the datagrid. In this case, you should have:
// example code..
Alert = EIcons.NEW;
AlertText = "new";
Alert = EIcons.NOICON;
AlertText = "noicons";
you can make it by using DataGridViewImageColumn

Categories

Resources