How do I receive back all the data in a loop? - c#

I wrote a C# code that will send functions ( 1-9) to a micro controller and the controller will send back data to my computer via RS232(SERIAL PORT). My only problem is i would like to automate it by sending the functions (1-9) and receiving them from the controller automatically. By doing this, I used a for loop but it is only displaying the data received from the last function sent, function 9 . However, i would like it to display all data receive. How can I display all the data received that the controller is sending back? Any suggestions?
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.Ports;
using System.Timers;
using System.IO;
using System.Net;
using System.Threading;
namespace SMCData
{
public partial class Form1 : Form
{
SerialPort _serialPort = new SerialPort();
public Form1()
{
InitializeComponent();
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataRecivedHandler);
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comport.Items.Add(s);
}
}
// settup connection
void setport()
{
//checking if Baud_Rate_txt is blank
string temp1 = Baud_Rate_txt.Text;
if (temp1 == "")
{
_serialPort.BaudRate = 9600;
}
else
{
_serialPort.BaudRate = int.Parse(Baud_Rate_txt.Text);
}
/* if (comport.SelectedIndex == -1)
{
ErrorBox.Text = " Need Com Port name";
return;
} */
_serialPort.PortName = comport.Text;//comport.SelectedItem.ToString();
_serialPort.DataBits = 8;
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.RtsEnable = true;
_serialPort.DtrEnable = true;
switch (HandshakeCB.Text)
{
case "None":
_serialPort.Handshake = Handshake.None;
break;
case "XOnXOff":
_serialPort.DtrEnable = true;
_serialPort.Handshake = Handshake.XOnXOff;
break;
}
switch (Parity_CB.Text)
{
case "None":
_serialPort.Parity = Parity.None;
break;
case "Even":
_serialPort.Parity = Parity.Even;
break;
case "Odd":
_serialPort.Parity = Parity.Odd;
break;
}
// Looks for user input on the desired Stop Bits of Application
switch (StopBitsCB.Text)
{
case "1":
_serialPort.StopBits = StopBits.One;
break;
case "2":
_serialPort.StopBits = StopBits.Two;
break;
case "None":
_serialPort.StopBits = StopBits.None;
break;
}
try
{
_serialPort.Open();
}
catch (UnauthorizedAccessException ex)
{
errorbox.Text = ex.Message + System.Environment.NewLine;
}
}
//Data Receive Fucntion
private void DataRecivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
int temp2;
string data;
int temp =sp.BytesToRead;
byte[] array = new byte[temp];
temp2 = sp.Read(array, 0, temp);
if (this.DataRecived.InvokeRequired)
{
DataRecived.BeginInvoke((Action)(() =>
{
data = Encoding.Default.GetString(array) ;
processdata(data);
DataRecived.Text = DataRecived.Text + data + System.Environment.NewLine;
}));
}
}
private void Dispose(RichTextBox dataRecived)
{
throw new NotImplementedException();
}
private void sendBLN_Click(object sender, EventArgs e)
{
// byte[] array_out = Encoding.ASCII.GetBytes(SendTXT.Text);
//_serialPort.Write(array_out, 0, array_out.Length);
// byte[] array_out2 = new byte[1];
//array_out2[0] = 0xD; //Encoding.ASCII.GetBytes("\r");
// byte[] array_out3 = { 141 };
//_serialPort.Write(array_out2, 0, array_out2.Length);
// _serialPort.Write(array_out3, 0, array_out3.Length);
//automate the process by sending 1,2,3,etc
for (int i = 0; i < 10; i++)
{
string c = Convert.ToString(i);
byte[] array_out = Encoding.ASCII.GetBytes(c); //convert i to the right variable type;
_serialPort.Write(array_out, 0, array_out.Length);
byte[] array_out2 = new byte[1];
array_out2[0] = 0xD;
_serialPort.Write(array_out2, 0, array_out2.Length);
//print what you receive
}
}
private void Refresh_btn_Click(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comport.Items.Remove(s);
}
foreach (string s in SerialPort.GetPortNames())
{
comport.Items.Add(s);
}
}
private void Connectbtn_Click(object sender, EventArgs e)
{
try
{
if (!_serialPort.IsOpen)
errorbox.Text = errorbox.Text + "Connected..." + System.Environment.NewLine;
setport();
}
catch (Exception ex )
{
errorbox.Text = errorbox.Text + ex.Message + System.Environment.NewLine;
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
_serialPort.Close();
errorbox.Text = " Disconnect";
}
private void button2_Click(object sender, EventArgs e)
{
DataRecived.Text = " ";
errorbox.Text = " ";
}
private void DataRecived_TextChanged(object sender, EventArgs e)
{
}
void processdata(string data)
{
if (data.Contains("No Action") == true)
{
return;
}
else if (data.Contains("Array Volt") == true)
{
string[] temp = data.Split('=');
temp[1].Trim('\r');
}
}
private void button3_Click(object sender, EventArgs e)
{
byte[] array_out2 = new byte[1];
array_out2 = Encoding.ASCII.GetBytes("\r");
_serialPort.Write(array_out2, 0, array_out2.Length);
}
private void SendTXT_TextChanged(object sender, EventArgs e)
{
}
private void comport_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Related

Return values from serial data received to another function

I am taking serial data from a distance sensor through Arduino to Visual Studio and I have another machine that is controlled by another controller.
Return values from serial data received to another function.
My question is: how to return the values from the function?
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
to a while loop inside the function
private void btnMove_Click(object sender, EventArgs e)
My code is as follows:
using System;
using System.Windows.Forms;
using PokeysLibSR;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace Melexis
{
public partial class Form1 : Form
{
PokeysLib pokeys;
public Form1()
{
InitializeComponent();
serialPort1.BaudRate = 9600;
serialPort1.PortName = "COM3";
}
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Open();
}
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string line = serialPort1.ReadLine();
string yourPortStringFormatted = Regex.Replace(line, #"\t|\n|\r", "");
string yourPortStringFormatted1 = yourPortStringFormatted.Trim();
double portNum = Double.Parse(yourPortStringFormatted1);
string line1 = Convert.ToString(portNum / 100);
this.BeginInvoke(new LineReceivedEvent(LineReceived), line1);
}
catch { }
finally
{
GC.Collect();
}
}
private delegate void LineReceivedEvent(string line1);
private void LineReceived(string line1)
{
textBox1.Text = line1;
}
private void btnMove_Click(object sender, EventArgs e)
{
double[] coords = new double[4] { 0, 0, 0, 0 };
byte axisMask = 0;
if (double.TryParse(tbX.Text, out coords[0])) axisMask = (byte)(axisMask + 1);
if (double.TryParse(tbY.Text, out coords[1])) axisMask = (byte)(axisMask + 2);
if (double.TryParse(tbZ.Text, out coords[2])) axisMask = (byte)(axisMask + 4);
while (true)
{
pokeys.StartMove(false, rbAbsolut.Checked, 1, coords);
Thread.Sleep(5000);
coords[0] = -coords[0];
pokeys.StartMove(false, rbAbsolut.Checked, 4, coords);
coords[2] = coords[2] + 10;
Thread.Sleep(5000);
}
}
}

Filtering scanned MAC address and display in textbox or listbox without duplication

Tool Image Winform
I am working on a tool that connected to my Bluetooth receiver and scan and get MAC address of BLE devices. So far I can scan and have the mac address continuously display in textbox. I am having problem with filtering MAC address?(Our assigned MAC address 88 99 66 55 4X XX the last 12 bit is free to use). How can I filter this while scanning and put it in Listbox or Textbox for later use.
public SerialPort serialport;
private bool buttonWasClicked = false;
public Form1()
{
InitializeComponent();
foreach (string s in SerialPort.GetPortNames())
{
cmPort.Items.Add(s);
}
}
public void serialport_connect(String port, int baudrate)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
serialport = new SerialPort(port, baudrate);
try
{
serialport.Open();
textBox1.AppendText(" OPEN " + "[" + dtn + "] " + " Port Opened: Connected\n");
// Event Handler
serialport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
//TextBox.CheckForIllegalCrossThreadCalls = false;
if (buttonWasClicked == true)
{
ThreadSafeDelegate(delegate { ScanList.Items.Add(serialport.ReadExisting()); });
//ThreadSafeDelegate(delegate { textBox3.Text += "\r\n"; });
}
else
{
ThreadSafeDelegate(delegate { textBox1.AppendText(serialport.ReadExisting()); });
ThreadSafeDelegate(delegate { textBox1.Text += "\r\n"; });
//textBox1.AppendText(serialport.ReadExisting());
//textBox1.Text += "\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{
byte[] msg = ASCIIEncoding.ASCII.GetBytes(textBox2.Text + "\0");
serialport.Write(msg, 0, msg.Length);
}
private void button2_Click(object sender, EventArgs e)
{
String port = cmPort.Text;
int baudrate = Convert.ToInt32(cmBaud.Text);
//Parity parity = (Parity)Enum.Parse(typeof(Parity), cmbparity.Text);
//int databits = Convert.ToInt32(cmbdatabits.Text);
//StopBits stopbits = (StopBits)Enum.Parse(typeof(StopBits), cmbstopbits.Text);
button3.Enabled = true;
serialport_connect(port, baudrate);
}
private void button3_Click(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
if (serialport.IsOpen)
{
serialport.Close();
button3.Enabled = false;
button2.Enabled = true;
textBox1.AppendText("[" + dtn + "] " + "Port Close: Disconnected\n");
}
}
private void btnClear_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
private void ThreadSafeDelegate(MethodInvoker method)
{
if (InvokeRequired)
BeginInvoke(method);
else
method.Invoke();
}
private void Scan_Click(object sender, EventArgs e)
{
buttonWasClicked = true;
byte[] msg = ASCIIEncoding.ASCII.GetBytes( "SNS10" + "\0");
serialport.Write(msg, 0, msg.Length);
}
}
}

Multi serialPort connection

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.Ports;
using System.IO;
using System.Threading;
namespace wangxl{
public partial class Smart_meter : Form
{
public int begin_year;
public int begin_month;
public int begin_day;
public int finish_year;
public int finish_month;
public int finish_day;
string from_bs_2;
string from_EM;
double[,] power = new double[4, 23];
int chushihua = 0;
int chuqi_changshu = 0;
int n_1 = 0;
int n_2 = 0;
double[,] power_display_f = new double[4, 23];
string path = "C:\\Users\\Public\\data\\data_logging.txt";
string path_m = "C:\\Users\\Public\\data\\energy_monitoring.txt";
// string path = "‪C:\\energy_moniotring\\data_logging.txt";
public Smart_meter()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
String[] input = SerialPort.GetPortNames();
comboBox1.Items.AddRange(input);
comboBox16.Items.AddRange(input);
}
void button1(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataBits = Convert.ToInt32(comboBox3.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox4.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox5.Text);
serialPort1.Open();
progressBar1.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
progressBar1.Value = 0;
}
}
private void button3_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
string output;
output = textBox2.Text;
serialPort1.Write(output);
textBox2.Text = "";
from_bs_2 = "";
serialPort1.DiscardOutBuffer();
// serialPort1.DiscardOutBuffer();
}
}
void button7_Click(object sender, EventArgs e)
{
try
{
serialPort2.PortName = comboBox16.Text;
serialPort2.BaudRate = Convert.ToInt32(comboBox15.Text);
serialPort2.DataBits = Convert.ToInt32(comboBox13.Text);
serialPort2.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox14.Text);
serialPort2.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox12.Text);
serialPort2.Open();
progressBar2.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button8_Click(object sender, EventArgs e)
{
if (serialPort2.IsOpen)
{
serialPort2.Close();
progressBar2.Value = 0;
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_bs_2 += serialPort1.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata));
Thread.Sleep(1000);
}
private void serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_EM += serialPort2.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata_2));
Thread.Sleep(1000);
// textBox1.Text += "laishujule";
}
I want to design a program which can connect 2 or 3 Arduinos at same time. So, I created a serialPort 1, it works well, I can receive the data from serial 1, but when I use the same way to create serialPort 2, I find the serialPort doesn't work, it can be connected, but it can't get any data from Arduino. I found that the serialPort2_DataReceived function doesn't work, I had add the serialPort 2 into my program from tools. Can you help me?
In your code, you are not specifying the SerialDataReceivedEventHandler for each SerialPort. Try adding the lines in your code before opening the serial:
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort2.DataReceived += new SerialDataReceivedEventHandler(serialPort2_DataReceived);
void button1(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataBits = Convert.ToInt32(comboBox3.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox4.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox5.Text);
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort1.Open();
progressBar1.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void button7_Click(object sender, EventArgs e)
{
try
{
serialPort2.PortName = comboBox16.Text;
serialPort2.BaudRate = Convert.ToInt32(comboBox15.Text);
serialPort2.DataBits = Convert.ToInt32(comboBox13.Text);
serialPort2.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox14.Text);
serialPort2.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox12.Text);
serialPort2.DataReceived += new SerialDataReceivedEventHandler(serialPort2_DataReceived);
serialPort2.Open();
progressBar2.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Listening to multiple clients with TCP server

We are just making a small quiz with TCP server. We can connect one client to the server but with multiple the server crashes. Ignore the dutch in it.
It can be that there are some non-logic things in it cause we have been playing with it for some hours.
Our code for the server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
namespace Simpele_Server
{
class Program
{
const int portNr = 2000;
static void Main(string[] args)
{
Program obj = new Program();
string antwoord = "";
string client1Ant = "";
string client2Ant = "";
string client3ant = "";
System.Net.IPAddress localAddress = System.Net.IPAddress.Parse("10.145.4.43");
//Luister op het eigen IP-adres: 127.0.0.1 (Loop back adres)
TcpListener mijnListener = new TcpListener(localAddress, portNr);
mijnListener.Start();
Console.WriteLine("\n Wachten op verbinding...\n");
while (true)
{
//Aanvaard het binnenkomende verzoek
TcpClient eenClient = mijnListener.AcceptTcpClient();
//Gebruik een 'NetworkStream object' om gegevens te verzenden en te ontvangen
NetworkStream ns = eenClient.GetStream();
byte[] data = new byte[eenClient.ReceiveBufferSize];
//Lees de binnenkomende 'stream' --> Read() is een 'blocking call'
int numBytesRead = ns.Read(data, 0,System.Convert.ToInt32(eenClient.ReceiveBufferSize));
antwoord = Encoding.ASCII.GetString(data, 0, numBytesRead);
if (antwoord.Substring(0, 8).Equals("Client1:"))
{
client1Ant = antwoord;
Console.WriteLine(obj.ControleerAntwoorden1(client1Ant));
}
if (antwoord.Substring(0, 8).Equals("Client2:"))
{
client1Ant = antwoord;
Console.WriteLine(obj.ControleerAntwoorden2(client2Ant));
}
if (antwoord.Substring(0, 8).Equals("Client3:"))
{
client1Ant = antwoord;
Console.WriteLine(obj.ControleerAntwoorden3(client3ant));
}
//Beeld de ontvangen data af
Console.WriteLine("Ontvangen: " + antwoord);
}
//Voorkom onmiddellijk sluiten van het venster
Console.ReadLine();
}
private int ControleerAntwoorden1(string antwoord)
{
int punten = 0;
string antw;
antw = antwoord.Replace("Client1:", "");
//antw = antwoord.Replace("Client2:", "");
//antw = antwoord.Replace("Client3:", "");
Console.WriteLine(antw);
string ant1 = antw.Substring(0, 1);
string ant2 = antw.Substring(1, 1);
string ant3 = antw.Substring(2, 1);
string ant4 = antw.Substring(3, 1);
if (ant1.Equals("1"))
punten++;
if (ant2.Equals("2"))
punten++;
if (ant3.Equals("3"))
punten++;
if (ant4.Equals("4"))
punten++;
return punten;
}
private int ControleerAntwoorden2(string antwoord)
{
int punten = 0;
string antw;
//antw = antwoord.Replace("Client1:", "");
antw = antwoord.Replace("Client2:", "");
//antw = antwoord.Replace("Client3:", "");
Console.WriteLine(antw);
string ant1 = antw.Substring(0, 1);
string ant2 = antw.Substring(1, 1);
string ant3 = antw.Substring(2, 1);
string ant4 = antw.Substring(3, 1);
if (ant1.Equals("1"))
punten++;
if (ant2.Equals("2"))
punten++;
if (ant3.Equals("3"))
punten++;
if (ant4.Equals("4"))
punten++;
return punten;
}
private int ControleerAntwoorden3(string antwoord)
{
int punten = 0;
string antw;
//antw = antwoord.Replace("Client1:", "");
//antw = antwoord.Replace("Client2:", "");
antw = antwoord.Replace("Client3:", "");
Console.WriteLine(antw);
string ant1 = antw.Substring(0, 1);
string ant2 = antw.Substring(1, 1);
string ant3 = antw.Substring(2, 1);
string ant4 = antw.Substring(3, 1);
if (ant1.Equals("1"))
punten++;
if (ant2.Equals("2"))
punten++;
if (ant3.Equals("3"))
punten++;
if (ant4.Equals("4"))
punten++;
return punten;
}
}
}
Our client:
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.Net.Sockets;
namespace client
{
public partial class Form1 : Form
{
const int poortNr = 2000;
//string ipadres = "127.0.0.1";
string ipadres = "10.145.4.43";
string strRead = null;
int intBytesRead;
string[] vragen = { "1. In welk jaar is 9/11 gebeurt?" + Environment.NewLine + " A = 2001" + Environment.NewLine + " B = 2000 " + Environment.NewLine + " C = 1999" + Environment.NewLine + " D = 1998",
"2. Welke kleur heeft een wolk?" + Environment.NewLine + " A = Blauw " + Environment.NewLine + " B = Groen " + Environment.NewLine + " C = Wit " + Environment.NewLine + " D = geel",
"3. Leeft Steve Jobs nog? " + Environment.NewLine + " A = Nee " + Environment.NewLine + " B = Ja " + Environment.NewLine + " C = Steve jobs heeft nooit bestaan " + Environment.NewLine + " D = test",
"4. test"};
string antwoorden = "";
int counter;
int aantalcounter = 2;
int vraagnr = 0;
TcpClient mijnClient = new TcpClient();
private void startTimer()
{
counter = aantalcounter;
timer1.Start();
timer1.Interval = 1000;
}
private void resetTimer()
{
counter = aantalcounter;
timer1.Stop();
timer1.Start();
}
private void stopTimer()
{
timer1.Stop();
}
public NetworkStream getNS()
{
//networkstream
NetworkStream mijnNS = mijnClient.GetStream();
return mijnNS;
}
public void disableRadiobuttons()
{
radioButton1.Enabled = false;
radioButton2.Enabled = false;
radioButton3.Enabled = false;
radioButton4.Enabled = false;
}
public void uncheckRadiobuttons()
{
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
}
//verzend data naar server
public void verzendData(string tekst)
{
byte[] aDataTeVersturen = Encoding.ASCII.GetBytes(tekst);
getNS().Write(aDataTeVersturen, 0, aDataTeVersturen.Length);
}
//zoek selected antwoord
public string getAntwoord()
{
string qsdf = "Client1: ";
string answer = "";
if (radioButton1.Checked == true)
{
answer = "1";
}
if (radioButton2.Checked == true)
{
answer = "2";
}
if (radioButton3.Checked == true)
{
answer = "3";
}
if (radioButton4.Checked == true)
{
answer = "4";
}
if (radioButton1.Checked == false && radioButton2.Checked == false && radioButton3.Checked == false && radioButton4.Checked == false)
{
answer = "0"; //geen antwoord
}
qsdf += answer;
return qsdf;
}
//alle antwoorden opslaan in lange string
public void opslaanAntwoorden(string antwoord)
{
antwoorden += antwoord;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
txtVraag.Text = vragen[vraagnr];
startTimer();
try
{
mijnClient.Connect(ipadres, poortNr);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnVerbreek_Click(object sender, EventArgs e)
{
getNS().Close();
mijnClient.Close();
Application.Exit();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void txtAntwoord_TextChanged(object sender, EventArgs e)
{
}
private void btnOntvang_Click(object sender, EventArgs e)
{
//data van server krijgen
byte[] aDataOntvangen = new byte[Convert.ToInt32(mijnClient.ReceiveBufferSize)];
intBytesRead = getNS().Read(aDataOntvangen, 0, Convert.ToInt32(mijnClient.ReceiveBufferSize));
strRead = Encoding.ASCII.GetString(aDataOntvangen, 0, intBytesRead);
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void txtVraag_TextChanged(object sender, EventArgs e)
{
}
private void timer1_Tick_1(object sender, EventArgs e)
{
txtCount.Text = counter.ToString();
counter--;
if (counter == -1)
{
resetTimer();
startTimer();
opslaanAntwoorden(getAntwoord()); //antwoorden opslaan in 1 lange string
if (vraagnr != vragen.Length-1)
{
txtVraag.Text = vragen[vraagnr + 1];
volgendeVraag();
uncheckRadiobuttons();
}
else
{
verzendData(antwoorden); //zend alle antwoorden (einde van quiz)
txtVraag.Text = "Einde van quiz";
uncheckRadiobuttons();
disableRadiobuttons();
//timer op 0 + stoppen
stopTimer();
counter = 0;
txtCount.Text = counter.ToString();
}
}
}
private void volgendeVraag()
{
vraagnr++;
}
private void label2_Click(object sender, EventArgs e)
{
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void lblCount_Click(object sender, EventArgs e)
{
}
}
}

Deleting items from listbox raises exception

I need to be able to delete items from a listbox but when I press the delete function and say yes I want to delete I get this exception: Items collection cannot be modified when the DataSource property is set.
Now I want to know what to do about this.
namespace Flashloader
{
public partial class Form1 : Form
{
private controllerinifile _controllerIniFile;
private toepassinginifile _toepassingIniFile;
// private Toepassinglist _toepassingList;
private StringList _comPorts;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
button4.Visible = false;
_controllerIniFile = new controllerinifile();
_toepassingIniFile = new toepassinginifile(_controllerIniFile.Controllers);
// _toepassingList = new Toepassinglist(_controllerList).FromIniFile();
_comPorts = new StringList();
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
_applicationListBox.Refresh();
_controllercombobox.Refresh();
Settings settings = _toepassingIniFile.Settings;
textBox3.Text = settings.Port;
textBox4.Text = settings.Baudrate;
}
// File select Button and file directory
private void button2_Click(object sender, EventArgs e)
{
appfile.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
{
if (appfile.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = appfile.FileName;
appfile.Title = ("Choose a file");
appfile.InitialDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.ExecutablePath), #"C:\\\\Projects\\flashloader2013\\mainapplication\\");
textBox1.Text = string.Format("{0}", appfile.FileName);
}
// textbox for the bootfile
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
// start button for sending appfiles
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
serialPort1.Open();
if (MessageBox.Show(appfile.FileName + " is selected and ready to be send,Are you sure you want to send the selected file?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The selected file will not be send.", "", MessageBoxButtons.OK);
}
else
{
button1.Visible = false;
button4.Visible = true;
}
try
{
using (FileStream inputstream = new FileStream(OpenBoot.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 32 * 1024 * 1024, FileOptions.SequentialScan))
{
byte[] buffer = new byte[8 * 1024 * 1024];
long bytesRead = 0, streamLength = inputstream.Length;
inputstream.Position = 0;
while (bytesRead < streamLength)
{
long toRead = streamLength - bytesRead;
if (toRead < buffer.Length)
buffer = new byte[(int)toRead];
if (inputstream.Read(buffer, 0, buffer.Length) != buffer.Length)
throw new Exception("File read error");
bytesRead += buffer.Length;
serialPort1.Write(buffer, 0, buffer.Length);
}
}
}
catch
{
MessageBox.Show("No file selected");
}
StringList list = new StringList().FromFile(appfile.FileName);
// Read file and put it in a list that will be sorted.
foreach (String line in list)
{
list.Sort();
serialPort1.Write(line);
}
MessageBox.Show("Bootfile and Applicationfile are send succesfully.");
}
// abort button for sending files
private void button4_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
button4.Visible = false;
button1.Visible = true;
progressBar1.Value = 0;
timer1.Enabled = false;
serialPort1.Close();
}
// backgroundworkers
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DateTime start = DateTime.Now;
e.Result = "";
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(50);
backgroundWorker1.ReportProgress(i, DateTime.Now);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
TimeSpan duration = DateTime.Now - start;
e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
DateTime time = Convert.ToDateTime(e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
}
}
private void Boot_button_Click(object sender, EventArgs e)
{
OpenBoot.Filter = "Binary Files (.BIN; .md6; .md7)|*.BIN; *.md6; *.md7|All Files (*.*)|*.*";
{
if (OpenBoot.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = OpenBoot.FileName;
OpenBoot.Title = ("Choose a file");
OpenBoot.InitialDirectory = "C:\\Projects\\flashloader2013\\mainapplication\\Bootfiles";
textBox2.Text = string.Format("{0}", OpenBoot.FileName);
}
// Saving the settings to the INI file.
private void SaveSettings()
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
MessageBox.Show("No Application selected");
return;
}
toepassing.Controller = (Controller)_controllercombobox.SelectedItem;
toepassing.Lastfile = textBox1.Text;
// toepassing.TabTip =
_toepassingIniFile.Save();
}
private Controller GetCurrentController()
{
int index = _controllercombobox.SelectedIndex;
if (index < 0)
return null;
return _controllerIniFile.Controllers[index];
}
private Toepassing GetCurrentApplication()
{
int index = _applicationListBox.SelectedIndex;
if (index < 0)
return null;
return _toepassingIniFile.ToePassingen[index];
}
private void typelistbox_SelectedIndexChanged(object sender, EventArgs e)
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
// TODO velden leegmaken
}
else
{
// appfile.InitialDirectory = Path.GetDirectoryName(controller.Lastfile);
appfile.FileName = toepassing.Lastfile;
textBox1.Text = toepassing.Lastfile;
_controllercombobox.SelectedItem = toepassing.Controller;
}
}
private void _controllercombobox_SelectedIndexChanged(object sender, EventArgs e)
{
Controller controller = GetCurrentController();
if (controller == null)
{
// TODO velden leegmaken
}
else
{
textBox2.Text = controller.Bootfile;
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void changeCurrentControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controlleredit = new Controlleredit(_controllerIniFile);
controlleredit.Show();
Refresh();
}
private void addControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controllersettings = new Newcontroller(_controllerIniFile);
controllersettings.ShowDialog();
_controllercombobox.DataSource = null;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
// Refresh();
// _controllercombobox.Refresh();
}
private void newapplicationBtton_Click(object sender, EventArgs e)
{
var newapplication = new NewApplication(_toepassingIniFile);
newapplication.ShowDialog();
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
/////////////////////////////The Error is down here /////////////////////////////
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
this._applicationListBox.Items.RemoveAt(this._applicationListBox.SelectedIndex);
}
}
}
The error says it quite clearly: you have to remove the item from the underlying datasource, you can't delete it manually. If you want to remove/add items manually, you shouldn't use databinding but build the list by hand.
As exception say you can't delete items directly from ListBox - you have to remove it from underlying DataSource and then rebind control (if it is not bound to BindingSource for example)
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
{
var item = this.GetCurrentApplication();
_toepassingIniFile.ToePassingen.Remove(item);
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
}
Your code is hard to read so I was a bit guessing with classes etc, but it should work.
Try to remove from datasource itself as below:
string myobj = this._applicationListBox.SelectedValue.ToString();
data.Remove(myobj );
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = data;
As others have said. You must have a list that is bound to the listbox. You cannot delete from the listbox directly.
You should delete from the List
private Toepassinglist _toepassingList
That is the datasource for your listbox.
Delete the item you want like so...
this._toepassingList.Items.RemoveAt(this._applicationListBox.SelectedIndex);
You can delete from list:---
ListName.Items.RemoveAt(postion);

Categories

Resources