Error creating a line graph on winform - c#

I keep getting this error when trying to initialise the form with my graph on it. Can't figure out a work around for it. Think it has something to do with Data Binding
Any ideas ?
Here is my code -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace NoCAnalysisTool2
{
public partial class Visualisation : UserControl
{
public string tx_graph { get; set; }
public List<int> tx_graphData { get; set; }
public Visualisation(string txGraph, List<int> tx_GData)
{
InitializeComponent();
tx_graph = txGraph;
tx_graphData = tx_GData;
// Set 3D chart settings
chart1.ChartAreas["Default"].Area3DStyle.Enable3D = true;
chart1.ChartAreas["Default"].Area3DStyle.IsRightAngleAxes = false;
chart1.ChartAreas["Default"].Area3DStyle.Inclination = 40;
chart1.ChartAreas["Default"].Area3DStyle.Rotation = 20;
chart1.ChartAreas["Default"].Area3DStyle.LightStyle = LightStyle.Realistic;
// Populate series with random data
Random random = new Random();
for (int pointIndex = 0; pointIndex < 10; pointIndex++)
{
chart1.Series["Series1"].Points.AddY(random.Next(45, 95));
chart1.Series["Series2"].Points.AddY(random.Next(5, 75));
}
// Set series chart type
chart1.Series["Series1"].ChartType = SeriesChartType.Line;
chart1.Series["Series2"].ChartType = SeriesChartType.Spline;
// Set point labels
chart1.Series["Series1"].IsValueShownAsLabel = true;
chart1.Series["Series2"].IsValueShownAsLabel = true;
// Enable X axis margin
chart1.ChartAreas["Default"].AxisX.IsMarginVisible = true;
// Enable the ShowMarkerLines
chart1.Series["Series1"]["ShowMarkerLines"] = "true";
chart1.Series["Series2"]["ShowMarkerLines"] = "true";
}
private void TxGraph_Load(object sender, EventArgs e)
{
}
private void Tx_graph_Click(object sender, EventArgs e)
{
}
private void Visualisation_Load(object sender, EventArgs e)
{
}
private void chart11_Click(object sender, EventArgs e)
{
}
}
}

The 'default' ChartArea is not called "Default" but "ChartArea1".
Trying to access an indexer by a wrong name results in an Argument Exeption.
You have the choice of either calling it by its index:
ChartArea ca = chart1.ChartAreas[0];
Or by its right name:
ChartArea ca = chart1.ChartAreas["ChartArea1"];
Or set the Name property th a string you like..:
chart1.ChartAreas[0].Name = "Default";
..and then calli it by that Name:
chart1.ChartAreas["Default"].Area3DStyle.Enable3D = true;
Btw: I hope you have added the 2nd Series in the designer and given it the right Name ;-)

Related

How can I display an image embedded in my program using the value from a random number generator?

I'm trying to build a Russian Roulette style program where you click a button and it randomly selects one of 25 images to display on screen but I can't seem to figure out how to call the images using the generator.
It works fine when I select an image manually, as seen in my code below, but anything else seems to return an error.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label_click(object sender, EventArgs e)
{
Close();
}
int mouseX = 0, mouseY = 0;
bool mouseDown;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
private void GOBUTN_Paint(object sender, PaintEventArgs e)
{
}
//Sharing is caring: Communism goes here
private System.Windows.Forms.Timer timtim;
int rand0;
PictureBox Rooskie = new PictureBox();
Label test = new Label();
Random rando = new Random();
List<int> duplicheck = new List<int>();
private void boopthesnoot(object sender, EventArgs e)
{
dingding:
//Hell yeah, random numbers here
rand0 = rando.Next(1, 26);
/*string combowombo = string.Join(", ", duplicheck.ToArray());
test.Text = combowombo;
test.Font = new Font("Calibri", 20);
Controls.Add(test);
test.Location = new Point(0, 200);
test.Height = 1000;
test.Width = 1000;*/
if(duplicheck.Contains(rand0))
{
goto dingding;
}
else
{
GOBUTTON.Hide();
pictureBox1.Hide();
pictureBox2.Hide();
//Fuckin image code goes here my dood
Rooskie.Width = 1160;
Rooskie.Height = 620;
Bitmap image = new Bitmap(WindowsFormsApp1.Properties.Resources._1);
Rooskie.Dock = DockStyle.Fill;
Rooskie.Image = (Image)image;
Controls.Add(Rooskie);
Rooskie.SizeMode = PictureBoxSizeMode.CenterImage;
//Aww shit, it's that timer time
timtim = new System.Windows.Forms.Timer();
timtim.Tick += new EventHandler(clockfinish);
timtim.Interval = 3000;
timtim.Start();
duplicheck.Add(rand0);
if (duplicheck.Count == 25)
{
duplicheck = new List<int>();
}
}
}
private void clockfinish(object sender, EventArgs e)
{
//CEASE THE TIMER AND GIVE ME BACK MY BUTTON
Rooskie.Image = null;
timtim.Stop();
GOBUTTON.Show();
pictureBox1.Show();
pictureBox2.Show();
}
The expected result is when the user presses the button it calls up the image without having to load it from a folder.

Change the format of the axis tick labels in LiveCharts

I just can't find a solution for changing the format of the y-axis tick labels.
Now I get labels like 0.03 and 0.035. But I always need three digits behind the decimal point.
The big question is, how to access the label format?
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using LiveCharts;
using LiveCharts.Helpers;
using LiveCharts.Wpf;
using LiveCharts.Wpf.Charts.Base;
using Brushes = System.Windows.Media.Brushes;
using Color = System.Windows.Media.Color;
using MessageBox = System.Windows.Forms.MessageBox;
namespace LiveAnalysis
{
public partial class Form1 : Form
{
List<DateTime> xvals = new List<DateTime>();
List<double> yvals = new List<double>();
private int _amountValues;
private int _startValue;
private List<double> _yvalsRange;
public Form1()
{
InitializeComponent();
// event
cartesianChart2.DataClick += CartesianChart1OnDataClick;
hScrollBar1.ValueChanged += (sender, e) => hScrollBar1_ValueChange(sender, e, hScrollBar1.Value);
// get original data
using (var db = new Analysis.DataClasses1DataContext())
{
var lttResults = db.LttResults;
var par1 = 0.0;
foreach (var data in lttResults)
{
if (data.GatewayEventType == 41)
par1 = data.FloatValue;
if (data.GatewayEventType != 42) continue;
var par2 = data.FloatValue;
var diff = Math.Round(par1 - par2, 3);
yvals.Add(diff);
xvals.Add(data.DateTime);
}
}
// chart settings
ChartSettings();
}
private void ChartSettings()
{
// performance
cartesianChart2.DisableAnimations = true;
cartesianChart2.DataTooltip = null;
cartesianChart2.Hoverable = false;
_startValue = 0;
_amountValues = 400;
_yvalsRange = yvals.GetRange(_startValue, _startValue + _amountValues);
// series setting
ScatterSeries scatterSeries1 = new ScatterSeries("Series1");
cartesianChart2.Series.Add(scatterSeries1);
scatterSeries1.Values = _yvalsRange.AsChartValues();
scatterSeries1.MaxPointShapeDiameter = 10;
scatterSeries1.Title = "Series1";
cartesianChart2.AxisX.Add(new Axis
{
Name = "xAxis",
Title = "DateTime",
FontSize = 22,
Foreground = System.Windows.Media.Brushes.Black,
MinValue = 0,
MaxValue = _amountValues,
});
cartesianChart2.AxisY.Add(new Axis
{
Name = "yAxis",
Title = "Time difference",
FontSize = 22,
Foreground = System.Windows.Media.Brushes.Black,
MinValue = -0.025,
MaxValue = 0.04,
});
}
private void CartesianChart1OnDataClick(object sender, ChartPoint chartPoint)
{
label1.Text = $#"You clicked: {chartPoint.X},{chartPoint.Y}";
}
private void button2_Click_1(object sender, EventArgs e)
{
}
private void hScrollBar1_ValueChange(object sender, EventArgs e, int value)
{
RedrawGraph(value);
}
private void RedrawGraph(int value)
{
_startValue = value * 10;
_yvalsRange = yvals.GetRange(_startValue, _startValue + _amountValues);
cartesianChart2.Series[0].Values = _yvalsRange.AsChartValues();
cartesianChart2.AxisX[0].MinValue = _startValue;
cartesianChart2.AxisX[0].MaxValue = _startValue + _amountValues;
}
}
}
The answer is:
Func<double, string> formatFunc = (x) => string.Format("{0:0.000}", x);
cartesianChart2.AxisY.Add(new Axis
{
LabelFormatter = formatFunc,
});

How can I delete all Panels from my calendar?

I'm programming an calendar with C# right now.
If i call my calendar, it creates as much panels as the current month has days. But if I want to increase the current month by one, the panels from the current month are stilt there.
So i have to delete all my panels as soon as I change the month.
But how can i do it in this case ?
Thanks for the help.
Code eplain:
First I call the createPanel method, to create panels for the current month.
Next if I click the MonthAdd method, I want to delete all my created panels.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;
namespace Einteilungs_Plan
{
public partial class Kalender : Form
{
public DateTime TodayDate { get; set; }
int counting = 0;
public Kalender()
{
InitializeComponent();
//Kalenderwochen initialisieren
monat(counting);
createPanel(true);
}
public string monat(int adding)
{
string monat = DateTime.Now.AddMonths(adding).ToString("MMMM");
tbMonat.Text = monat;
return monat;
}
private void btnAddMonth_Click(object sender, EventArgs e)
{
counting++;
if(counting < 12)
{
monat(counting);
switch (counting)
{
case 0:
int number = 10;
break;
case 1:
break;
default:
break;
}
}
else
{
counting--;
}
}
private void btnRemoveMonth_Click(object sender, EventArgs e)
{
counting--;
if (counting > -1)
{
monat(counting);
}
else
{
counting++;
}
}
public void createPanel(bool remove)
{
var numDays = DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month);
int locationX = 12;
int locationY = 74;
for (int i = 0; i <= numDays; i++)
{
//Create Panel
Panel test = new Panel();
//Fill Panel
test.Name = "panel" + i;
test.Width = 200;
test.Height = 100;
test.BackColor = Color.White;
test.Location = new System.Drawing.Point(locationX, locationY);
this.Controls.Add(test);
test.Show();
if(i == 6 || i == 13 || i == 20 || i == 28)
{
locationY += 106;
locationX = -194;
}
locationX += 206;
}
}
public void Kalender_Shown(object sender, EventArgs e)
{
}
private void Kalender_Load(object sender, EventArgs e)
{
}
private void btnNeuerEintrag_Click(object sender, EventArgs e)
{
Formular formular = new Formular();
formular.Show();
formular.Focus();
}
private void btnHinzufügen_Click(object sender, EventArgs e)
{
Formular formular = new Formular();
formular.Show();
formular.Focus();
}
}
}
...
for (int i = 0; i <= numDays; i++)
{
//Create Panel
test[i] = new Panel();
}
...
and then
this.Control.Remove(test[i]);
I'm not sure if I undestood you well but first simple solutiona that comes into my mind is that while creating panels you can keep them in some List for example and before generating new month you can call
foreach (var p in panels)
this.Controls.Remove(p);

C# label string to int conversion error

I am making a very small RPG game in C# to practice some skill (and to have fun!). I have gotten pretty far with the images, buttons and such.
My issue is that I am being thrown an error when trying to convert my label strings into integers to be compared for my attackingPhase() method.
Here is my code and a screenshot of the error.
I believe my code is correct but I can not figure out as to why the error is being thrown.
Thank you for all help.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RPG
{
public partial class Form2 : Form
{
private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
pictureBox1.Image = mainForm.MyPictureBoxEnemy.Image;
pictureBox2.Image = mainForm.MyPictureBoxHero.Image;
lbl_Health_Value_Enemy.Text = "100";
lbl_Health_Value_Hero.Text = "100";
}
public void attackingPhase()
{
Random rnd = new Random();
int enemy_damage = rnd.Next(1, 25);
int hero_damage = rnd.Next(2, 15);
var enemyHealth = Convert.ToInt32(lbl_Health_Value_Enemy);
var heroHealth = Convert.ToInt32(lbl_Health_Value_Hero);
if((enemyHealth & heroHealth) > 0)
{
enemyHealth = enemyHealth - enemy_damage;
heroHealth = heroHealth - hero_damage;
} else
{
MessageBox.Show("DEAD");
}
lbl_Health_Value_Enemy.Text = enemyHealth.ToString();
lbl_Health_Value_Hero.Text = heroHealth.ToString();
}
private void btnAttack_Click(object sender, EventArgs e)
{
attackingPhase();
}
}
}
You need to convert the Text property of a label,
var enemyHealth = Convert.ToInt32(lbl_Health_value_Enemy.Text);
var heroHealth = Convert.ToInt32(lbl_Health_Value_Hero.Text);

How to remove PictureBoxes dynamically?

I am trying to make pictureboxes fall continuously in the form.
Here is the code that I tried.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Rain_dropz
{
public partial class Form1 : Form
{
PictureBox[] RD = new PictureBox[500];
int ndrop = 0;
public Form1()
{
InitializeComponent();
}
public void dropIt()
{
for (int i = 0; i < ndrop; i++)
{
RD[i].Top += 10;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
Random rnd = new Random();
int l = rnd.Next(1,545);
RD[ndrop] = new PictureBox();
RD[ndrop].BackColor = System.Drawing.Color.MediumBlue;
RD[ndrop].Size = new Size(5, 5);
RD[ndrop].Location = new Point(l, 0);
this.Controls.Add(RD[ndrop]);
ndrop++;
dropIt();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
}
}
I think it is better to delete the picture boxes which disappear from the form. How to do that?
You can remove it by removing the picturebox from form controls list.
private void timer1_Tick(object sender, EventArgs e)
{
Random rnd = new Random();
int l = rnd.Next(1,545);
RD[ndrop] = new PictureBox();
RD[ndrop].BackColor = System.Drawing.Color.MediumBlue;
RD[ndrop].Size = new Size(5, 5);
RD[ndrop].Location = new Point(l, 0);
RD[ndrop].LocationChanged += pb_LocationChanged;
this.Controls.Add(RD[ndrop]);
ndrop++;
dropIt();
}
void pb_LocationChanged(object sender, EventArgs e)
{
// FORM_LASTBOUND is the Y-Axis point after which you wanted to remove the picturebox.
if ((sender as PictureBox).Top > FORM_LASTBOUND)
{
this.Controls.Remove(sender as PictureBox);
}
}

Categories

Resources