I want to drawing real time chart in c# with my data that read from serial port Arduino device i didn't know how can i do this with c#.
i want 2d and 3d chart in my program anyone can help me ?
in my program i read data from serial port and time of data has been arrived so my chart be have 2 data one of them is info and another is time.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using port.dbDataSetTableAdapters;
using System.Threading.Tasks;
namespace Factory_Performance
{
public partial class FrmMain : Form
{
int sfs = 0;
string filename;
string line;
string s;
string temp="";
string temp1="";
Series series = new Series();
SerialPort ComPort = new SerialPort();
internal delegate void SerialDataReceivedEventHandlerDelegate(object sender, SerialDataReceivedEventArgs e);
internal delegate void SerialPinChangedEventHandlerDelegate(object sender, SerialPinChangedEventArgs e);
private SerialPinChangedEventHandler SerialPinChangedEventHandler1;
delegate void SetTextCallback(int ReadByte);
int InputData = 0;
private int CountData;
private string StrData;
double[] Values;
public FrmMain()
{
InitializeComponent();
SerialPinChangedEventHandler1 = new SerialPinChangedEventHandler(PinChanged);
ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
}
private double calculate_input(int s2, int s3)
{
return double.Parse(s2.ToString() + "/" + s3.ToString());
}
private void GetAllIDInDB()
{
tblIDTableAdapter.Fill(dbDataSet.TblID);
CmbID.Items.Clear();
for (int i = 0; i < dbDataSet.TblID.Rows.Count; i++)
CmbID.Items.Add(dbDataSet.TblID.Rows[i]["ID"].ToString());
}
private void GetAllID_DetailsInDB(int ID)
{
tblID_DetailsTableAdapter.FillByID(dbDataSet.TblID_Details, ID);
listreadtxt.Items.Clear();
for (int i = 0; i < dbDataSet.TblID_Details.Rows.Count; i++)
listreadtxt.Items.Add(dbDataSet.TblID_Details.Rows[i]["Value"].ToString());
}
private void GetInfoPorts()
{
try
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
cboPorts.Items.Clear();
cboBaudRate.Items.Clear();
cboStopBits.Items.Clear();
cboParity.Items.Clear();
cboHandShaking.Items.Clear();
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(8);
cboDataBits.Items.Add(7);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
catch
{
MessageBox.Show("خطا در گرفتن اطلاعات پورت");
}
}
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = ComPort.ReadByte();
object firstByte = InputData;
if (ComPort.IsOpen==true)
{
s = Convert.ToString(Convert.ToChar(firstByte));
temp1 += s;
lock (firstByte) {
if (Convert.ToInt32(firstByte) == 13)
{
temp = temp1;
temp1 = "";
ComPort.DiscardInBuffer();
ComPort.DiscardOutBuffer();
LstGetInfo.BeginInvoke(new Action(()=>
{
if (temp !=null)
{
LstGetInfo.Items.Add(temp);
if (LstGetInfo.Items.Count >= 100)
{
LstGetInfo.Items.Clear();
}
FileStream fs = new FileStream(filename, FileMode.Append);
var data = System.Text.Encoding.UTF8.GetBytes(String.Format("{0} {1}", temp, DateTime.Now.ToString("hh mm ss")) +"\r\n");
fs.Write(data, 0, data.Length);
fs.Close();
}
}));
LstGetInfo.BeginInvoke(new Action(() =>
{
LstGetInfo.TopIndex = LstGetInfo.Items.Count - 1;
}));
}
}
}
}
internal void PinChanged(object sender, SerialPinChangedEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = (int)StrData[i];
Array.Reverse(Values);
chart1.Titles.Clear();
chart1.Titles.Add(TxtTitle.Text);
chart1.Series.Clear();
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(TxtTitleSeries.Text + " " + i.ToString(), Values[i]);
chart1.Series.Add(series);
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void CmbPalette_SelectedIndexChanged(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
private void FrmMain_Load(object sender, EventArgs e)
{
chart2.Series.Clear();
// TODO: This line of code loads data into the 'dbDataSet.TblID_Details' table. You can move, or remove it, as needed.
this.tblID_DetailsTableAdapter.Fill(this.dbDataSet.TblID_Details);
// TODO: This line of code loads data into the 'dbDataSet.TblID' table. You can move, or remove it, as needed.
this.tblIDTableAdapter.Fill(this.dbDataSet.TblID);
GetInfoPorts();
CmbPalette.SelectedIndex = 1;
CmbChartType.SelectedIndex = 4;
CountData = 0;
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
GetInfoPorts();
}
private void btnPortState_Click(object sender, EventArgs e)
{
if (sfs == 1) {
try
{
if (btnPortState.Text == "ارتباط با دستگاه")
{
temp1 = "";
temp = "";
btnPortState.Text = "قطع ارتباط با دستگاه";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
LstGetInfo.Items.Clear();
}
else if (btnPortState.Text == "قطع ارتباط با دستگاه")
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
}
}
catch
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
MessageBox.Show("خطا در انجام عملیات");
}
}
else
{
MessageBox.Show("برای ذخیزه فایل محلی را انتخاب کنید");
}
}
private void button1_Click_1(object sender, EventArgs e)
{
savedata();
}
private void savedata()
{
try
{
if (LstGetInfo.Items.Count < 0) return;
int ItemCount = int.Parse(listreadtxt.Items[0].ToString());
int ItemIDCount = 0;
int ItemID = 0;
int ItemValue1 = 0, ItemValue2 = 0;
TblIDTableAdapter tblid = new TblIDTableAdapter();
TblID_DetailsTableAdapter tblid_details = new TblID_DetailsTableAdapter();
tblid.DeleteAllID();
LstGetInfo.Items.RemoveAt(0);
for (int i = 0; i < ItemCount; i++)
{
ItemID = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
tblid.Insert(ItemID);
if (LstGetInfo.Items.Count > 0)
{
ItemIDCount = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
for (int j = 0; j < ItemIDCount; j += 2)
{
ItemValue1 = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
ItemValue2 = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
tblid_details.Insert(ItemID, calculate_input(ItemValue1, ItemValue2));
}
}
}
}
catch
{
// MessageBox.Show("در ساخت نمودار مشکلی پیش آمده است");
try
{
LstGetInfo.Items.RemoveAt(0);
}
catch
{
}
}
finally
{
GetAllIDInDB();
}
ShowChart();
}
private void CmbID_SelectedIndexChanged(object sender, EventArgs e)
{
GetAllID_DetailsInDB(int.Parse(CmbID.Text));
if (listreadtxt.Items.Count > 0)
ShowChart();
}
private void CmbPalette_SelectedIndexChanged_1(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged_1(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
private void ShowChart()
{
CountData =listreadtxt.Items.Count;
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = double.Parse(listreadtxt.Items[i].ToString());
chart1.Titles.Clear();
chart1.Titles.Add(TxtTitle.Text);
chart1.Series.Clear();
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(TxtTitleSeries.Text + " " + i.ToString(), Values[i]);
chart1.Series.Add(series);
}
private void button3_Click_3(object sender, EventArgs e)
{
GetAllIDInDB();
}
private void button4_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = string.Empty;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) {
listreadtxt.Items.Clear();
Stream fs = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(fs);
while ((line = reader.ReadLine()) != null)
{
listreadtxt.Items.Add(line);
}
reader.Close();
}
}
public void button5_Click(object sender, EventArgs e)
{
dateTimePicker1.BeginInvoke(new Action(() =>
{
DialogResult result1 = saveFileDialog1.ShowDialog();
dateTimePicker1.Format = DateTimePickerFormat.Custom;
string formatvalue =Convert.ToString( dateTimePicker1.Value.Date.ToString(" yyyy-MM-dd"));
filename = saveFileDialog1.FileName + formatvalue + ".csv";
if (result1==DialogResult.OK)
{
sfs = 1;
}
}));
}
private void button6_Click(object sender, EventArgs e)
{
try {
ComPort.Close();
CountData = LstGetInfo.Items.Count;
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = double.Parse(LstGetInfo.Items[i].ToString());
chart2.Titles.Clear();
chart2.Titles.Add(TxtTitle.Text);
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(System.DateTime.Now, Values[i]);
chart2.Series.Add(series);
}
catch
{
LstGetInfo.Items.Remove(0);
}
finally
{
ComPort.Open();
}
}
}
}
The problem is that in line
series.Points.AddXY(System.DateTime.Now, Values[i]);
you are adding points with the same X value set to System.DateTime.Now. In result you have only one point on axis X.
I found solution for my problem
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Threading.Tasks;
using System.Threading;
namespace chart
{
public partial class Form1 : Form
{
string s;
int InputData = 0;
private delegate void CanIJust();
Series series = new Series();
private List<int> _valuelist;
private Thread _thread;
private CanIJust _DoIt;
private Random _ran;
private int _interval;
private List<double> _timelist;
private List<int> _customValueList;
SerialPort ComPort = new SerialPort();
int sfs = 0;
string temp = "";
string temp1 = "";
public Form1()
{
InitializeComponent();
chart1.ChartAreas[0].AxisX.IsStartedFromZero = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = false;
chart1.Series[0].XValueType = ChartValueType.Time;
chart1.ChartAreas[0].AxisX.ScaleView.SizeType = DateTimeIntervalType.Seconds;
chart1.ChartAreas[0].AxisX.IntervalAutoMode = IntervalAutoMode.FixedCount;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Seconds;
chart1.ChartAreas[0].AxisX.Interval = 0;
_valuelist = new List<int>();
_ran = new Random();
_interval = 500;
tbupdateinterval.Text = "500";
GoBoy();
_timelist = new List<double>();
_customValueList = new List<int>();
}
private void GetInfoPorts()
{
try
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
cboPorts.Items.Clear();
cboBaudRate.Items.Clear();
cboStopBits.Items.Clear();
cboParity.Items.Clear();
cboHandShaking.Items.Clear();
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(8);
cboDataBits.Items.Add(7);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
catch
{
MessageBox.Show("خطا در گرفتن اطلاعات پورت");
}
}
private void GoBoy()
{
_DoIt += new CanIJust(AddData);
DateTime now = DateTime.Now;
chart1.ChartAreas[0].AxisX.Minimum = now.ToOADate();
chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(10).ToOADate();
_thread = new Thread(new ThreadStart(ComeOnYouThread));
_thread.Start();
}
private void ComeOnYouThread()
{
while (true)
try
{
chart1.Invoke(_DoIt);
Thread.Sleep(_interval);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Exception:" + e.ToString());
}
}
private void AddData()
{
DateTime now = DateTime.Now;
InputData = ComPort.ReadByte();
object firstByte = InputData;
if (ComPort.IsOpen == true)
{
s = Convert.ToString(Convert.ToChar(firstByte));
temp1 += s;
lock (firstByte)
{
if (Convert.ToInt32(firstByte) == 13)
{
temp = temp1;
temp1 = "";
ComPort.DiscardInBuffer();
ComPort.DiscardOutBuffer();
_valuelist.Add(Convert.ToInt32(temp));
chart1.ResetAutoValues();
if (chart1.Series[0].Points.Count > 0)
{
while (chart1.Series[0].Points[0].XValue < now.AddSeconds(-5).ToOADate())
{
chart1.Series[0].Points.RemoveAt(0);
chart1.ChartAreas[0].AxisX.Minimum = chart1.Series[0].Points[0].XValue;
chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(5).ToOADate();
}
}
chart1.Series[0].Points.AddXY(now.ToOADate(), _valuelist[_valuelist.Count - 1]);
chart1.Invalidate();
}
}
}
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (_thread != null)
_thread.Abort();
}
private void btn_2D_Click_1(object sender, EventArgs e)
{
btn_2D.Enabled = false;
btn_3D.Enabled = true;
chart1.ChartAreas[0].Area3DStyle.Enable3D = false;
}
private void btn_3D_Click_1(object sender, EventArgs e)
{
btn_2D.Enabled = true;
btn_3D.Enabled = false;
chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
}
private void btn_add_Click(object sender, EventArgs e)
{
_customValueList.Add(_ran.Next(0, 100));
_timelist.Add(DateTime.Now.ToOADate());
updatesecondChart();
}
private void updatesecondChart()
{
chart2.Series[0].Points.AddXY(_timelist[_timelist.Count - 1], _customValueList[_customValueList.Count-1]);
chart2.Invalidate();
}
private void btn_serialize_Click(object sender, EventArgs e)
{
}
private void btn_updateInterval_Click(object sender, EventArgs e)
{
int interval = 0;
if (int.TryParse(tbupdateinterval.Text, out interval))
{
if (interval > 0)
_interval = interval;
else
MessageBox.Show("بازه زمانی باید بیشتر از 0 باشند");
}
else
{
MessageBox.Show("I nappropriate Data.");
}
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
GetInfoPorts();
}
private void btnPortState_Click(object sender, EventArgs e)
{
//if (sfs == 1)
//{
try
{
if (btnPortState.Text == "ارتباط با دستگاه")
{
temp1 = "";
temp = "";
btnPortState.Text = "قطع ارتباط با دستگاه";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
AddData();
}
else if (btnPortState.Text == "قطع ارتباط با دستگاه")
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
}
}
catch
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
MessageBox.Show("خطا در انجام عملیات");
}
}
//else
//{
// MessageBox.Show("برای ذخیزه فایل محلی را انتخاب کنید");
//}
//}
private void CmbPalette_SelectedIndexChanged_1(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
}
}
Related
I am having an issue with my C# application, it runs fine or x amount of minutes but hits an error at some point which complains about 'InvaildOperationException Collection was modified'. I am quite new to C# and i am unable to find the solution even after reading other posts.
From what i can tell after reading the posts it is something to do with my for loop, could anyone be so kind as to tell me what i have done wrong.
The error i think is caused by the UpdateGraph function.
The code is designed to connect to a Cisco router and get the cellular data via Serial and show it in a graph and richTextBox which is all working minus the error i get at some point :(
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Cisco_Cellular_Diagnostics
{
public partial class Form1 : Form
{
SerialPort serialPort;
string[] ports;
string rawStrings;
int ComPort_ComboBoxIndex;
bool serialIsOpen = false;
bool autoScroll = false;
readonly String executingFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
TextWriter txtFile;
List<int> bandwidthArray = new List<int>();
List<int> rssiArray = new List<int>();
List<int> rsrpArray = new List<int>();
List<int> rsrqArray = new List<int>();
List<int> snrArray = new List<int>();
List<int> nearbyCellsArray = new List<int>();
private static System.Timers.Timer pollingTimer;
public Form1()
{
InitializeComponent();
ports = SerialPort.GetPortNames();
ToolTip toolTip1 = new ToolTip
{
AutoPopDelay = 5000,
InitialDelay = 500,
ReshowDelay = 500,
ShowAlways = true
};
ComPortComboBox.Items.AddRange(ports);
ComPortComboBox.SelectedIndex = 0;
autoScroll = true;
pollingTimer = new System.Timers.Timer(5000);
pollingTimer.Elapsed += new ElapsedEventHandler(SendCellularCmd);
Console.WriteLine("executingFolder = " + executingFolder);
String fileDate = DateTime.Today.ToString("d").Replace("/", "-");
txtFile = new StreamWriter(executingFolder + "\\Cisco Celluar log " + fileDate + ".txt", true);
LoadChart();
}
private void LoadChart()
{
var chart = chart1.ChartAreas[0];
chart.AxisX.IntervalType = DateTimeIntervalType.Number;
chart.AxisX.LabelStyle.Format = "";
chart.AxisY.LabelStyle.Format = "";
chart.AxisX.LabelStyle.IsEndLabelVisible = true;
chart.AxisX.Minimum = 0;
chart.AxisY.Minimum = -128;
chart.AxisY.Maximum = 128;
chart.AxisX.Interval = 1;
chart.AxisY.Interval = 16;
chart1.Series[0].IsVisibleInLegend = false;
chart.AxisX.Title = "Reading";
chart.AxisY.Title = "dB";
//chart1.Series[0].XValueType = ChartValueType.DateTime;
chart1.Series.Add("Bandwidth");
chart1.Series["Bandwidth"].ChartType = SeriesChartType.Line;
chart1.Series["Bandwidth"].Color = Color.Green;
chart1.Series["Bandwidth"].BorderWidth = 8;
chart1.Series.Add("RSSI");
chart1.Series["RSSI"].ChartType = SeriesChartType.Line;
chart1.Series["RSSI"].Color = Color.Blue;
chart1.Series["RSSI"].BorderWidth = 8;
chart1.Series.Add("RSRP");
chart1.Series["RSRP"].ChartType = SeriesChartType.Line;
chart1.Series["RSRP"].Color = Color.Yellow;
chart1.Series["RSRP"].BorderWidth = 8;
chart1.Series.Add("RSRQ");
chart1.Series["RSRQ"].ChartType = SeriesChartType.Line;
chart1.Series["RSRQ"].Color = Color.Red;
chart1.Series["RSRQ"].BorderWidth = 8;
chart1.Series.Add("SNR");
chart1.Series["SNR"].ChartType = SeriesChartType.Line;
chart1.Series["SNR"].Color = Color.Purple;
chart1.Series["SNR"].BorderWidth = 8;
chart1.Series.Add("Nearby cells");
chart1.Series["Nearby cells"].ChartType = SeriesChartType.Line;
chart1.Series["Nearby cells"].Color = Color.DarkGray;
chart1.Series["Nearby cells"].BorderWidth = 8;
chart1.Series["Bandwidth"].Points.AddXY(0, 0);
chart1.Series["RSSI"].Points.AddXY(0, 0);
chart1.Series["RSRP"].Points.AddXY(0, 0);
chart1.Series["RSRQ"].Points.AddXY(0, 0);
chart1.Series["SNR"].Points.AddXY(0, 0);
chart1.Series["Nearby cells"].Points.AddXY(0, 0);
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
BeginInvoke((MethodInvoker)delegate ()
{
rawStrings += indata;
//txtFile.Write(indata);
//txtFile.WriteLine(DateTime.Now + "\n");
ReceivedDataRichTextBox.AppendText(indata);
if (autoScroll)
ReceivedDataRichTextBox.ScrollToCaret();
});
}
private void OpenSerial_Click(object sender, EventArgs e)
{
ComPort_ComboBoxIndex = ComPortComboBox.SelectedIndex;
if (ComPort_ComboBoxIndex >= 0 && !serialIsOpen)
{
try
{
string selectedCOM = ComPortComboBox.SelectedItem.ToString();
serialPort = new SerialPort(selectedCOM, 9600);
serialPort.ReadTimeout = 3000;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DataBits = 8;
serialPort.Handshake = Handshake.None;
serialIsOpen = true;
serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
OpenSerialOne.Text = "Close Serial";
serialPort.Open();
LogIntoCLI();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else if (serialIsOpen)
{
try
{
serialPort.Write("exit");
serialPort.Close();
txtFile.Close();
pollingTimer.Enabled = false;
serialIsOpen = false;
OpenSerialOne.Text = "Open Serial";
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
else
{
MessageBox.Show("Error, check the baud Rate and COM port is selected and try again.");
}
}
private void LogIntoCLI()
{
if (serialIsOpen)
{
try
{
serialPort.Write("\r");
Thread.Sleep(2000);
serialPort.Write("\r"); // "exit\r"
Thread.Sleep(2000);
serialPort.Write("enable\r");
Thread.Sleep(3000);
serialPort.Write("met0cean\r");
Thread.Sleep(2000);
pollingTimer.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void SendCellularCmd(object sender, ElapsedEventArgs e)
{
ExtractData();
serialPort.Write("show cell 0 radio\r");
Console.WriteLine("sending command...");
}
private void ExtractData()
{
try
{
txtFile.Write(rawStrings);
txtFile.WriteLine(DateTime.Now + "\n");
String[] listOfStrings = rawStrings.Split('\n');
rawStrings = "";
foreach (String value in listOfStrings)
{
String[] strlist = value.Split(' ');
if (value.IndexOf("Bandwidth") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "Bandwidth", ref bandwidthArray);
}
else if (value.IndexOf("RSSI") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSSI", ref rssiArray);
}
else if (value.IndexOf("RSRP") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSRP", ref rsrpArray);
}
else if (value.IndexOf("RSRQ") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSRQ", ref rsrqArray);
}
else if (value.IndexOf("SNR") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "SNR", ref snrArray);
}
else if (value.IndexOf("nearby cells") >= 0 && strlist.Length == 6)
{
if (int.TryParse(strlist[5], out int extractedValue))
UpdateGraph(extractedValue, "Nearby cells", ref nearbyCellsArray);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void UpdateGraph(int a_value, String a_ID, ref List<int> a_List)
{
try
{
// keep the list count to 20 items
if (a_List.Count == 20)
a_List.RemoveAt(0);
a_List.Add(a_value);
// clear chart and add items
chart1.Series[a_ID].Points.Clear();
for (int i = 0; i < a_List.Count; i++)
{
chart1.Series[a_ID].Points.AddXY(i, a_List[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing Application", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
try
{
txtFile.Close();
serialPort.Write("exit");
serialPort.Close();
pollingTimer.Enabled = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
break;
}
}
private void PollingTimeNumericUpDown_ValueChanged(object sender, EventArgs e)
{
pollingTimer.Interval = Convert.ToDouble(PollingTimeNumericUpDown.Value);
}
private void ClearDataButton_Click(object sender, EventArgs e)
{
ReceivedDataRichTextBox.Clear();
chart1.Series["Bandwidth"].Points.Clear();
chart1.Series["RSSI"].Points.Clear();
chart1.Series["RSRP"].Points.Clear();
chart1.Series["RSRQ"].Points.Clear();
chart1.Series["SNR"].Points.Clear();
chart1.Series["Nearby cells"].Points.Clear();
chart1.Series["Bandwidth"].Points.AddXY(0, 0);
chart1.Series["RSSI"].Points.AddXY(0, 0);
chart1.Series["RSRP"].Points.AddXY(0, 0);
chart1.Series["RSRQ"].Points.AddXY(0, 0);
chart1.Series["SNR"].Points.AddXY(0, 0);
chart1.Series["Nearby cells"].Points.AddXY(0, 0);
}
private void SendManualCmd_Click(object sender, EventArgs e)
{
try
{
serialPort.Write(textBox1.Text + "\r");
textBox1.Clear();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void ReloadComPortsButton_Click(object sender, EventArgs e)
{
ComPortComboBox.Items.Clear();
ports = SerialPort.GetPortNames();
ComPortComboBox.Items.AddRange(ports);
}
private void ComComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// CiscoComPort = ComPortComboBox.SelectedItem.ToString();
}
}
}
How created a simple slideshow with a PictureBox element.
Now I would like to open an image by clicking on it to see it in full resolution - with the default app which is associated with .jpg files (e.g. Microsoft Photos). I think a click event on the PictureBox would be the way to go but I don't know what code to add. Couldn't find a good example on the internet.
Following the code I use so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Diashow
{
public partial class Form1 : Form
{
private string[] folderFile = null;
private int selected = 0;
private int begin = 0;
private int end = 0;
public Form1()
{
InitializeComponent();
this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
folderBrowserDialog1.SelectedPath = #"E:\MiscTest\";
timer1.Interval = 5000;
}
private void btnOpen_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string[] part1 = null, part2 = null, part3 = null;
part1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");
part2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");
part3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.tif");
folderFile = new string[part1.Length + part2.Length + part3.Length];
Array.Copy(part1, 0, folderFile, 0, part1.Length);
Array.Copy(part2, 0, folderFile, part1.Length, part2.Length);
Array.Copy(part3, 0, folderFile, part1.Length + part2.Length, part3.Length);
selected = 0;
begin = 0;
end = folderFile.Length;
showImage(folderFile[selected]);
btnPrevious.Enabled = true;
btnNext.Enabled = true;
bntSlideshow.Enabled = true;
}
}
private void showImage(string path)
{
Image imgtemp = Image.FromFile(path);
pictureBox1.Image = imgtemp;
}
private void btnNext_Click(object sender, EventArgs e)
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (selected == 0)
{
selected = folderFile.Length - 1;
showImage(folderFile[selected]);
}
else
{
selected = selected - 1; showImage(folderFile[selected]);
}
}
private void nextImage()
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
}
nextImage();
}
private void bntSlideshow_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
timer1.Enabled = false;
bntSlideshow.Text = "START Slideshow";
}
else
{
timer1.Enabled = true;
bntSlideshow.Text = "STOP Slideshow";
}
}
}
}
Hello I'm trying to click a button to remove and item but I keep getting an
'IndexOutOfRange' Exception.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
clientNum = clientList.Items.Count;
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
if (dateSeletion[clientList.SelectedIndex] != null)
{
dateCalender.SelectionStart = todayDate[clientList.SelectedIndex];
Check();
}
else
{
nameLbl.Text = nameSeletion[clientList.SelectedIndex];
dateText.Text = "";
}
}
The if (dateSeletion[clientList.SelectedIndex] != null) is where I'm having the error.
The button code is
private void button1_Click(object sender, EventArgs e)
{
clientList.Items.Remove(clientList.Items[clientList.SelectedIndex]);
}
the dateSelection is defined in the save button and Initialization
private void SaveBtn_Click(object sender, EventArgs e)
{
//save the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
dateSeletion[clientList.SelectedIndex] = dateCalender.SelectionStart.Date.ToShortDateString() +
" " + clientTime.Value.ToShortTimeString();
todayDate[clientList.SelectedIndex] = dateCalender.SelectionStart;
dateCalender.BoldedDates = todayDate;
Check();
}
public ClientForm()
{
InitializeComponent();
clientNum = clientList.Items.Count;
todayDate = new DateTime[clientNum];
dateSeletion = new string[clientNum];
nameSeletion = new string[clientNum];
clientTime.CustomFormat = "hh:mm tt";
//initialize the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
}
Try this
clientList.RemoveAt(clientList.SelectedIndex);
I'm sorry that the title is confusing but I did not know how to ask this question; if someone can help with a better title I would appreciate it.
I am building a database of players and their match performance. The matches are displayed using a tab control, inside the matches are fields that are stored in a panel. The amount of matches goes up to 5, therefore each field is an array of size 5 to represent different values for different matches. I have ran into the problem of trying to save the amount of tabs (matches) there are for that unique player.
Because the amount of tabs carries over to the next player shown, I tried to iterate through all the matches and all the fields for that player, determine which matches contain empty fields and respectively delete that tab (match). So if player 1 has 3 matches with values in fields, but player 2 only has 2 matches that contain values in fields, the 3rd match (tab) will be deleted as the fields have no values.
to better explain, this is the GUI:
Picture
My attempt at iterating through the field of each match looks like this:
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
i++;
}
However I am presented with the error: Cannot implicitly convert type 'int' to 'int[]'
I would really appriciate if someone could help me out here, I understand that the code is long but It is organised and titled so that should help.
Full 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.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================DATA STRUCTURE ===========================
[Serializable]
private struct Player
{ //CONSTRUCTOR
public Player(int noOfMatches)
{
uniquePlayerId = new int[noOfMatches];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
matchesCount = 0;
csNumber = new int[noOfMatches];
killsNumber = new int[noOfMatches];
deathsNumber = new int[noOfMatches];
assistsNumber = new int[noOfMatches];
minutesNumber = new int[noOfMatches];
for (int i = 0; i < noOfMatches; ++i)
{
uniquePlayerId[i] = 0;
csNumber[i] = 0;
killsNumber[i] = 0;
deathsNumber[i] = 0;
assistsNumber[i] = 0;
minutesNumber[i] = 0;
}
}
//DATA TYPES
public int[] uniquePlayerId;
public int[] csNumber;
public int[] killsNumber;
public int[] deathsNumber;
public int[] assistsNumber;
public int[] minutesNumber;
public int matchesCount;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
//GLOBAL VARIABLES
public ArrayList GameDB;
public ArrayList playerMatch;
private int currentEntryShown = 0;
private int numberOfEntries = 0;
private string filename = "W:\\test.dat";
public string prevImage = "";
// =========================================================================
// ====================== STARTING POINT ===================================
// =========================================================================
public Form1()
{
InitializeComponent();
GameDB = new ArrayList();
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown < GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries;
currentEntryShown = numberOfEntries - 1;
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
ShowData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
numberOfEntries--;
GameDB.RemoveAt(currentEntryShown);
SaveData();
currentEntryShown--;
if (currentEntryShown <= GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.Title = "Select an image file";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.imagePath = openFileDialog1.FileName;
GameDB[currentEntryShown] = aNewStruct;
playerPictureBox.ImageLocation = openFileDialog1.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void searchBtn_Click(object sender, EventArgs e)
{
string toFind;
string source;
toFind = searchInput.Text;
toFind = toFind.ToLower();
for (int i = 0; i < GameDB.Count; ++i)
{
source = ((Player)GameDB[i]).playerIgName + ((Player)GameDB[i]).contactStreet;
source = source.ToLower();
if (source.Contains(toFind))
{
currentEntryShown = i;
ShowData();
UpdatePrevNextBtnStatus();
break;
}
if (i == (GameDB.Count - 1))
{
MessageBox.Show(toFind + " not found");
}
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void addNewMatchBtn_Click(object sender, EventArgs e)
{
TabPage newTP = new TabPage();
if (tabMatches.TabCount <= 4)
{
tabMatches.TabPages.Add(newTP);
int TabPageNumber = tabMatches.SelectedIndex + 1;
tabMatches.TabPages[TabPageNumber].Text = "Match " + (TabPageNumber + 1);
tabMatches.SelectTab(TabPageNumber);
deleteMatchBtn.Enabled = true;
panel1.Parent = tabMatches.SelectedTab;
}
ShowData();
}
private void deleteMatchBtn_Click(object sender, EventArgs e)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
int lastTabNumber = tabMatches.TabCount - 1;
tabMatches.SelectTab(lastTabNumber);
if (tabMatches.SelectedIndex < 1) deleteMatchBtn.Enabled = false;
}
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
GameDB[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
//Match data
private void tabMatches_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Parent = tabMatches.SelectedTab;
ShowData();
}
private void numCS_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.csNumber[tabMatches.SelectedIndex] = (int)numCS.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numKills_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.killsNumber[tabMatches.SelectedIndex] = (int)numKills.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numDeaths_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.deathsNumber[tabMatches.SelectedIndex] = (int)numDeaths.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numAssists_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.assistsNumber[tabMatches.SelectedIndex] = (int)numAssists.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numMinutes_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.minutesNumber[tabMatches.SelectedIndex] = (int)numMinutes.Value;
GameDB[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((Player)GameDB[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((Player)GameDB[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTelephone;
playerPictureBox.ImageLocation = ((Player)GameDB[currentEntryShown]).imagePath;
numCS.Value = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
numKills.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
numDeaths.Value = ((Player)GameDB[currentEntryShown]).deathsNumber[tabMatches.SelectedIndex];
numAssists.Value = ((Player)GameDB[currentEntryShown]).assistsNumber[tabMatches.SelectedIndex];
numMinutes.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, GameDB);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
GameDB = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = GameDB.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close();
Environment.Exit(1);
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
GameDB.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
}
// =========================================================================
// ====================== MISC STUFF =======================================
// =========================================================================
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void developerToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("By Szymon Zmudzki: 13042432");
}
}
}
Try change this
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To use the csNumber which is int[] in the for loop
int i = 0;
while (i < 5)
{
if (((Player)GameDB[currentEntryShown]).csNumber[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To find out the value of tabMatches.TabCount, add this line when you run the program and see it in the output window: (To answer your question, I would assume the TabCount start with 1. That's the default value of any .Count() call to an array of integer. But this is the best way to know for sure.)
System.Diagnostics.Debug.WriteLine(tabMatches.TabCount);
I have created a program for some class work and it all works fine, but I'm having some problems with the alignment of the multiple bits of info inserted into the list box on the same rows.
When I print it, it looks messy and also looks messy in the list box.
Is there anyway I can neaten it up a little? I've tried pad right with no joy and list views confuse the hell out of me. 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.Windows.Forms;
using Microsoft.VisualBasic;
using System.Collections;
namespace Assignment2
{
public partial class frmCalculator : Form
{
bool blnDot = false;
double dbAllPoints = 0;
double dbAllMoney = 0;
public frmCalculator()
{
InitializeComponent();
}
private void frmCalculator_Load(object sender, EventArgs e)
{
ddbItems.Items.Add("Glass");
ddbItems.Items.Add("Paper");
ddbItems.Items.Add("Beverage Cans");
ddbItems.Items.Add("Tins");
ddbItems.Items.Add("Milk Cartons");
ddbItems.Items.Add("Juice Boxes");
ddbItems.Items.Add("Plastics");
ddbItems.Items.Add("Clothes");
}
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '.'))
{
MessageBox.Show("Please input a number!", "Error");
e.Handled = true;
}
if (e.KeyChar == '.')
{
if (blnDot == true) { e.Handled = true; }
else { blnDot = true; }
}
}
private void txtInput_MouseClick(object sender, MouseEventArgs e)
{
txtInput.Text = "";
}
private void btnCalculate_Click(object sender, EventArgs e)
{
String strItem = "";
double dbMoney = 0;
double dbPoints = 0;
int intPoint = 0;
double dbWeight = 0;
if (((txtInput.Text == "")||(txtInput.Text=="Input the weight")|| (ddbItems.SelectedIndex==0)))
{
MessageBox.Show("Please input a weight into the textbox and make a selection from the drop down box", "Error");
}
else
{
if (ddbItems.SelectedIndex == 1)
{
intPoint = 7;
strItem = ddbItems.Items[1].ToString();
}
if (ddbItems.SelectedIndex == 2)
{
intPoint = 8;
strItem = ddbItems.Items[2].ToString();
}
if (ddbItems.SelectedIndex == 3)
{
intPoint = 10;
strItem = ddbItems.Items[3].ToString();
}
if (ddbItems.SelectedIndex == 4)
{
intPoint = 10;
strItem = ddbItems.Items[4].ToString();
}
if (ddbItems.SelectedIndex == 5)
{
intPoint = 3;
strItem = ddbItems.Items[5].ToString();
}
if (ddbItems.SelectedIndex == 6)
{
intPoint = 3;
strItem = ddbItems.Items[6].ToString();
}
if (ddbItems.SelectedIndex == 7)
{
intPoint = 5;
strItem = ddbItems.Items[7].ToString();
}
if (ddbItems.SelectedIndex == 8)
{
intPoint = 6;
strItem = ddbItems.Items[8].ToString();
}
dbWeight = Convert.ToDouble(txtInput.Text);
dbPoints = intPoint * dbWeight;
dbMoney = dbPoints * 0.01;
dbAllPoints = dbAllPoints + dbPoints;
dbAllMoney = dbAllMoney + dbMoney;
lblTotals.Visible = true;
lblTotals.Text = "You have " + dbAllPoints.ToString() + " points, and you have earned £" + dbAllMoney.ToString("0.00");
lstResults.Items.Add(strItem + " " + dbWeight.ToString() + "kg " + dbPoints.ToString() + " points £" + dbMoney.ToString("0.00"));
txtInput.Text = "Input the weight";
ddbItems.SelectedIndex = 0;
blnDot = false;
}
}
private void btnEnd_Click(object sender, EventArgs e)
{
frmWelcome frmWelcome = (frmWelcome)Application.OpenForms["frmWelcome"];
frmWelcome.Close();
this.Dispose();
}
private void btnReset_Click(object sender, EventArgs e)
{
DialogResult result;
result = MessageBox.Show("Are you sure you want to reset everything?", "Confirm", MessageBoxButtons.YesNo);
if (result == DialogResult.No) return;
txtInput.Text = "Input the weight";
lstResults.Items.Clear();
ddbItems.SelectedIndex = 0;
lblTotals.Text = "";
lblTotals.Visible = false;
blnDot = false;
}
private void btnPrint_Click(object sender, EventArgs e)
{
int intMax;
intMax = lstResults.Items.Count;
String[] arrResults = new String[intMax];
int intLoop;
for (intLoop = 0; intLoop < intMax; intLoop++)
{
arrResults[intLoop] = lstResults.Items[intLoop].ToString();
}
Array.Sort(arrResults);
lstResults.Items.Clear();
for (intLoop = 0; intLoop < intMax; intLoop++)
{
lstResults.Items.Add(arrResults[intLoop]);
}
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
String strLine = "";
int intLoop;
Font pfont = new Font("Verdana", 18, GraphicsUnit.Point);
int intLine = 75;
strLine = "Item Weight Points Money";
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
intLine = intLine + 30;
for (intLoop = 0; intLoop < lstResults.Items.Count; intLoop++)
{
strLine = strLine +lstResults.Items[intLoop];
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
intLine = intLine + 30;
strLine = "";
}
intLine = intLine + 30;
strLine = lblTotals.Text;
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
}
}
}
You should use a DataGridView control instead of a ListBox since you are trying to display "column" information.
Likewise, when printing, you should be doing the DrawString for each column as well so that they line up properly.
If you want to continue with what you are doing, then you should use a mono-spaced font like Courier, not Verdana, and count the spaces between then lengths of the words.