c# Invalid argument for Index, null value - c#

i just made a file editor, it contains a listview and a textbox, i made that when i select and item from the list view it appears in the textbox, the text is japanese, and when i select a japanese text or line, it gives me an error: InvalidArgument: Value '0' is not valid for 'index'
can you guys help me ? this is my code:
private void Form1_Load(object sender, EventArgs e)
{
}
private void menuItem2_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
textBox1.Text = "";
menuItem12.Text = "file type is: ";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.Filter = "All Files (*.*)|*.*";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = ofd.FileName;
BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.GetEncoding("SHIFT-JIS"));
foreach (char mychar in br.ReadChars(4)) menuItem12.Text += mychar;
if (menuItem12.Text != "file type is: TXTD")
{
MessageBox.Show("This is not a TXTD file...", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
br.BaseStream.Position = 0x8;
int Pntrnum = br.ReadInt16();
menuItem11.Visible = true;
menuItem11.Text = Pntrnum.ToString();
List<int> offsets = new List<int>();
br.BaseStream.Position = 0x10;
for (int i = 0; i < Pntrnum; i++)
{
offsets.Add(br.ReadInt32());
}
Dictionary<int, string> values = new Dictionary<int, string>();
for (int i = 0; i < offsets.Count; i++)
{
int currentOffset = offsets[i];
int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;
int stringLength = (nextOffset - currentOffset - 1) / 2;
br.BaseStream.Position = currentOffset;
var chars = br.ReadChars(stringLength);
values.Add(currentOffset, new String(chars));
}
foreach (int offset in offsets)
{
listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
br.Close();
br = null;
}
}
ofd.Dispose();
ofd = null;
}
private void menuItem4_Click(object sender, EventArgs e)
{
this.Close();
}
private void menuItem6_Click(object sender, EventArgs e)
{
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
int number_pointers = Convert.ToInt32(menuItem11.Text);
Encoding enc = Encoding.GetEncoding("SHIFT-JIS");
bw.BaseStream.Position = 0x10;
int curr_pointer = 4 + number_pointers * 4;
for (int i = 0; i < number_pointers; i++)
{
bw.Write(curr_pointer);
curr_pointer += enc.GetByteCount(listView1.Items[i].SubItems[1].Text) + 1;
}
for (int i = 0; i < number_pointers; i++)
bw.Write(enc.GetBytes(listView1.Items[i].SubItems[1].Text + '\0'));
bw.Flush();
bw.Close();
bw = null;
}
private void menuItem8_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Application.ExecutablePath;
sfd.Filter = "Text Files (*.txt)|*.txt";
sfd.Title = "Save Text file";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.Cancel)
return;
StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.GetEncoding("SHIFT-JIS"));
for (int i = 0; i < listView1.Items.Count; ++i)
{
string Ptrs = listView1.Items[i].SubItems[0].Text;
string Strs = listView1.Items[i].SubItems[1].Text;
wwrite.WriteLine(i.ToString() + " > " + Ptrs + " > " + Strs);
}
wwrite.Close();
}
private void menuItem5_Click(object sender, EventArgs e)
{
MessageBox.Show("TXTD Editor by Omarrrio v0.1 Alpha\n2013 Copyrighted crap and whatever", "About...", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
private void button1_Click(object sender, EventArgs e)
{
listView1.SelectedItems[0].SubItems[1].Text = textBox1.Text;
}
private void menuItem12_Click(object sender, EventArgs e)
{
}
}
}

Before accessing the SelectedItems index, you should check if there are any items selected.
private void button1_Click(object sender, EventArgs e)
{
if(listView1.SelectedItems.Count > 0)
textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
You may also want to perform a check to ensure that SubItems has an index of 1 before using it.

Related

Real Time Chart with Serial port Data in C#

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;
}
}
}

Removing an item from a listbox in C#

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);

How to reload a form

I have looking for the solution but still found nothing
Here is my code:
private void Form1_Load(object sender, EventArgs e)
{
RichTextBox rtb = new RichTextBox();
rtb.Text = File.ReadAllText(#"C:\Users\Admin\Desktop\myfile\customers.txt");
int i = 0;
foreach (string line in rtb.Lines)
{
if (line == "--")
{
ListViewItem item = new ListViewItem();
item.Text = rtb.Lines[i + 1];
item.SubItems.Add(rtb.Lines[i + 2]);
item.SubItems.Add(rtb.Lines[i + 3]);
item.SubItems.Add(rtb.Lines[i + 4]);
listView1.Items.Add(item);
}
i += 1;
}
}
private void button1_Click(object sender, EventArgs e)
{
Form2 pop = new Form2();
pop.ShowDialog();
string name = pop.name;
int age = int.Parse(pop.Age);
string dob = pop.DateOfBirth;
string addr = pop.Address;
StreamWriter write = new StreamWriter(#"C:\Users\Admin\Desktop\myfile\customers.txt",true);
write.Write("--\n");
write.Write("{0}\n",name);
write.Write("{0}\n",dob);
write.Write("{0}\n",age);
write.Write("{0}\n",addr);
write.Close();
}
The question is how do I reload the list view after I write the data into the text file?
Extract the logic out of Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
RefreshListView();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 pop = new Form2();
pop.ShowDialog();
string name = pop.name;
int age = int.Parse(pop.Age);
string dob = pop.DateOfBirth;
string addr = pop.Address;
StreamWriter write = new StreamWriter(#"C:\Users\Admin\Desktop\myfile\customers.txt",true);
write.Write("--\n");
write.Write("{0}\n",name);
write.Write("{0}\n",dob);
write.Write("{0}\n",age);
write.Write("{0}\n",addr);
write.Close();
RefreshListView();
}
private void RefreshListView()
{
listView1.Items.Clear();
RichTextBox rtb = new RichTextBox();
rtb.Text = File.ReadAllText(#"C:\Users\Admin\Desktop\myfile\customers.txt");
int i = 0;
foreach (string line in rtb.Lines)
{
if (line == "--")
{
ListViewItem item = new ListViewItem();
item.Text = rtb.Lines[i + 1];
item.SubItems.Add(rtb.Lines[i + 2]);
item.SubItems.Add(rtb.Lines[i + 3]);
item.SubItems.Add(rtb.Lines[i + 4]);
listView1.Items.Add(item);
}
i += 1;
}
}

How can Iterate and determine whether an array is empty in a tab control?

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);

Play video without using media player [Winform]

I want to play a video like that guy did [link].
I'm working on C# Windows Form Application (not NXA).
But I don't know how.
I tried using Microsoft.DirectX.AudioVideoPlayback but no luck.
This is what I tried so far :
OpenFileDialog rihanna = new OpenFileDialog();
if(rihanna.ShowDialog() == DialogResult.OK)
{
video = new Video(rihanna.FileName);
video.Owner = panel1;
video.Stop();
}
Now what can i do? I tried using video class but as I said it just did not work.
I'm able to compile but when I'm running the program, I don't see the form window.
using Microsoft.DirectX.AudioVideoPlayback;
namespace Play_Video
{
public partial class Form1 : Form
{
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
public Form1()
{
InitializeComponent();
VolumeTrackBar.Value = 4;
}
private void timer1_Tick(object sender, EventArgs e)
{
PlayingPosition = CalculateTime(vdo.CurrentPosition);
txtStatus.Text = PlayingPosition + "/" + Duration;
if (vdo.CurrentPosition >= vdo.Duration)
{
timer1.Stop();
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdo.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
else
vdoTrackBar.Value += 1;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
if (openFileDialog1.FileName != "")
{
Form1.ActiveForm.Text = openFileDialog.FileName + " - Anand Media Player";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (vdo != null)
{
if (vdo.Playing)
{
vdo.Pause();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
}
else
{
vdo.Play();
timer1.Start();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.pause;
}
}
}
private void btnStop_Click(object sender, EventArgs e)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
public string CalculateTime(double Time)
{
string mm, ss, CalculatedTime;
int h, m, s, T;
Time = Math.Round(Time);
T = Convert.ToInt32(Time);
h = (T / 3600);
T = T % 3600;
m = (T / 60);
s = T % 60;
if (m < 10)
mm = string.Format("0{0}", m);
else
mm = m.ToString();
if (s < 10)
ss = string.Format("0{0}", s);
else
ss = s.ToString();
CalculatedTime = string.Format("{0}:{1}:{2}", h, mm, ss);
return CalculatedTime;
}
private void VolumeTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Audio.Volume = CalculateVolume();
}
}
public int CalculateVolume()
{
switch (VolumeTrackBar.Value)
{
case 1:
return -1500;
case 2:
return -1000;
case 3:
return -700;
case 4:
return -600;
case 5:
return -500;
case 6:
return -400;
case 7:
return -300;
case 8:
return -200;
case 9:
return -100;
case 10:
return 0;
default:
return -10000;
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
}
private void vdoTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.CurrentPosition = vdoTrackBar.Value;
}
}
private void Form1_Load(object sender, EventArgs e)
{
MaximizeBox = false;
}
private void exitToolItem_Click(object sender,EventArgs e)
{
Application.Exit();
}
}
}
Okey Namespace is clear:
using Microsoft.DirectX.AudioVideoPlayback;
Some Global Variables in Form:
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
And now in your Button or what else to open:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
And in some other Button Code to Start/Pause:
if (vdo.Playing)
{
vdo.Pause();
btnPlay.Text= "Play";
}
else
{
vdo.Play();
btnPlay.Text= "Pause";
}
BTW:
Don't name variables/members or something else in your Code after Girls...
If your aren't sure how to name it, there are some Guidelines here.
The goal is to provide a consistent set of naming
conventions that results in names that make immediate sense to
developers.
For AudioVideoPlayback to work, you'll need to add the AudioVideoPlayback reference, with Reference > Add Reference > Browse > C: > Windows > Microsoft.Net > DirectX for managed code > 1.0.2902.0 > Microsoft.DirectX.AudioVideoPlayback.dll

Categories