The following code reads port data and writes the data into a textbox with timestemp once it differs from the previous one. Afterwards I can save the data to a textfile.
Instead of writing it into a textbox and then save it to text file per button, I would like it to auto append to the text file every x seconds (lets say 10). By reading through other questions I got some ideas but was not really able to execute them.
Anyone can help?
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
private string in_data_old = "";
public Form1()
{
InitializeComponent();
}
private void start_btn_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 9600;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open();
data_tb.Text = "";
}
catch(Exception ex) {
MessageBox.Show(ex.Message, "Error");
}
}
void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
if (in_data != in_data_old)
{
this.Invoke(new EventHandler(displaydata_event));
}
in_data_old = in_data;
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Year+ "." +datetime.Month+ "." + datetime.Day + " " + datetime.Hour+ ":" +datetime.Minute+ ":" +datetime.Second;
data_tb.AppendText(time + "\t\t\t\t\t" + in_data+"\n");
}
private void stop_btn_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void save_btn_Click(object sender, EventArgs e)
{
try
{
string pathfile = #"C:\Users\xy\Desktop\DATA\";
string filename = "light_data.txt";
System.IO.File.AppendAllText(pathfile + filename, data_tb.Text);
MessageBox.Show("Data has been saved to "+pathfile, "Save File");
}
catch(Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
}
Add a Timer , you can find it on the toolbox and you can set it's interval for any timer you would like and add your btn click functionality there example :
private void timer1_Tick(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 9600;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open();
data_tb.Text = "";
}
catch(Exception ex) {
MessageBox.Show(ex.Message, "Error");
}
}
Related
I want to connect to the wifi network opened from esp32 via c# program and view the data sent from esp32. I was doing this project before using arduino via serialport, but I need to do it with local wifi network and I couldn't find the necessary codes to connect to wifi network. Can you help me.
I made a small program using the BMP180 sensor. I show data in C# by transferring data via Arduino and C# program. In this program, I want to transfer data by using ESP32 and connecting to the wifi network (The ones shown in the picture are a program I made over serialport using arduino.
public partial class Form1 : Form
{
int line = 1;
int column = 1;
int lineNumber = 1;
public Form1()
{
InitializeComponent();
}
private string data;
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 1000;
chart1.ChartAreas[0].AxisY.Interval = 100;
chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
chart2.ChartAreas[0].AxisY.Minimum = 0;
chart2.ChartAreas[0].AxisY.Maximum = 100;
chart2.ChartAreas[0].AxisY.Interval = 10;
chart2.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
chart2.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
data = serialPort1.ReadLine();
this.Invoke(new EventHandler(displaydata));
}
private void displaydata(object sender, EventArgs e)
{
DateTime myDateValue = DateTime.Now;
textBox3.Text = myDateValue.ToString();
string[] value = data.Split(',');
textBox1.Text = value[0];
textBox2.Text = value[1];
string pressure = Convert.ToString(value[0]);
string temperature = Convert.ToString(value[1]);
this.chart1.Series[0].Points.AddXY(myDateValue.ToString("HH:mm:ss"), pressure); //zaman ve basınç değerini eksenlere ata
this.chart2.Series[0].Points.AddXY(myDateValue.ToString("HH:mm:ss"), temperature); //zaman ve sıcaklık değerini eksenlere ata
line = dataGridView1.Rows.Add();
dataGridView1.Rows[line].Cells[0].Value = lineNumber;
dataGridView1.Rows[line].Cells[1].Value = pressure;
dataGridView1.Rows[line].Cells[2].Value = temperature;
dataGridView1.Rows[line].Cells[3].Value = myDateValue.ToShortDateString();
dataGridView1.Rows[line].Cells[4].Value = myDateValue.ToLongTimeString();
line++;
lineNumber++;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = 9600;
serialPort1.Open();
button1.Enabled = false;
button2.Enabled=true;
label1.Text = "Connected.";
label1.ForeColor = Color.Green;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ("Error:"));
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
button1.Enabled = true;
button2.Enabled = false;
label1.Text = "Disconnected";
label1.ForeColor = Color.Red;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ("Error:"));
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Interval = 1000;
}
private void button3_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application uyg = new Microsoft.Office.Interop.Excel.Application();
uyg.Visible = true;
Microsoft.Office.Interop.Excel.Workbook kitap = uyg.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)kitap.Sheets[1];
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[1, i + 1];
myRange.Value2 = dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[j + 2, i + 1];
myRange.Value2 = dataGridView1[i, j].Value;
}
}
}
}
}
I think the best option is to use TCP/IP socket connection.
For the ESP32 there are some libraries like:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/lwip.html
And from C#:
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/using-tcp-services
I'm right now trying to read sensor data through USB-RS485 converter and utilizing the EasyModbus.dll in C#.
However, I've kept receiving CRC checked failed at the ReadHoldingRegister part. The connection and reading part is shown below.
I've already done lots of research but still can't solve the issue. Can anyone help me with this?
The CRC checked failed will occur at
int[] Read = modbusClient.ReadHoldingRegisters(179, 6);
The FT300 Modbus Setting is also shown below:
Image is stolen from this manual, page 34
void getavailableports() // get available COM
{
comboBox1.Items.Clear();
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void comboBox1_MouseClick(object sender, MouseEventArgs e) //let user choose COM
{
getavailableports();
}
private void Start_Click(object sender, EventArgs e) // Start button being pressed
{
try
{
Invoke(new EventHandler(ChangeColor));
//FT300Port.PortName = comboBox1.Text;
//.BaudRate = Convert.ToInt32(BaudRate.Text);
//FT300Port.Open();
modbusClient.UnitIdentifier = 9; // default slaveID = 1
modbusClient.Baudrate = Convert.ToInt32(BaudRate.Text); // default baudrate = 9600
modbusClient.Parity = System.IO.Ports.Parity.None;
modbusClient.StopBits = System.IO.Ports.StopBits.One;
modbusClient.ConnectionTimeout = 500;
modbusClient.Connect();
lb_status.Text = "Connected";
timer_Modbus.Enabled = true;
}
catch(Exception ex)
{
lb_status.Text = ex.ToString();
throw;
}
}
private void ChangeColor(object sender, EventArgs e)
{
Start.Text = "Streaming";
Start.BackColor = Color.Red;
}
private void Disconnect_Click(object sender, EventArgs e)
{
modbusClient.Disconnect();
Start.Text = "Start";
Start.BackColor = Color.DarkGray;
lb_status.Text = "Disconnected";
timer_Modbus.Enabled = false;
}
private void timer_Modbus_Tick(object sender, EventArgs e)
{
timer_Modbus.Enabled = false;
//modbusClient.WriteMultipleCoils(179, new bool[] { true, true, true, true, true, true});
//Write Coils starting with Address 180
//bool[] readCoils = modbusClient.ReadCoils(179, 6);
**int[] Read = modbusClient.ReadHoldingRegisters(179, 6);**
/*textBox1.Text = Convert.ToString(Read[0]);
textBox2.Text = Convert.ToString(Read[1]);
textBox3.Text = Convert.ToString(Read[2]);
textBox4.Text = Convert.ToString(Read[3]);
textBox5.Text = Convert.ToString(Read[4]);
textBox6.Text = Convert.ToString(Read[5]);*/
timer_Modbus.Enabled = true;
}
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);
}
}
}
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);
}
}
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);