Deleting items from listbox raises exception - c#

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

Related

Updating/Deleting a row in listview that includes a countdown timer

Currently i am having trouble updating a row in my listview that contains both text and a timer that counts down. So far I've tried updating the entire row as well as trying to update just the text and i get an error in each instance.
System.ArgumentOutOfRangeException: InvalidArgument=Value of '0' is not valid for 'index
I am also having a slight problem with the delete button. It deletes the row as planned but it appears the information is still running in the background and haven't come across any info on how to delete the session. I pray for your guidance.
private void Confirm_Click(object sender, EventArgs e)
{
CSession newSession = new CSession();
if(PasswordText.Text == "")
{
MessageBox.Show("Password not entered");
return;
}
newSession.password = PasswordText.Text;
newSession.purchased_time = workingTimeSpan;
newSession.remaining_time = workingTimeSpan;
newSession.status = "Online";
sessionlist.Add(newSession);
PasswordText.Text = "";
TimerLabel.Text = "";
workingTimeSpan = new TimeSpan();
}
private void DisplayAllSessions()
{
listView1.Items.Clear();
foreach(CSession c in sessionlist)
{
string[] row = { c.password, c.purchased_time.ToString(), c.remaining_time.ToString(), c.status };
ListViewItem i = new ListViewItem(row);
listView1.Items.Add(i);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach(CSession c in sessionlist)
{
if (c.remaining_time.TotalMinutes == 5 && !c.MessageDisplayed)
{
c.MessageDisplayed = true;
MessageBox.Show("Time almost up for client.");
}
if (c.remaining_time.TotalSeconds < 1)
{
c.status = "Offline";
}
if(c.status == "Online")
{
c.remaining_time -= oneSecond;
}
}
DisplayAllSessions();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void Reset_Click(object sender, EventArgs e)
{
}
private void updatebutton()
{
listView1.SelectedItems[0].SubItems[0].Text = PasswordText.Text;
PasswordText.Text = "";
}
private void Update_Click(object sender, EventArgs e)
{
updatebutton();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
PasswordText.Text = listView1.SelectedItems[0].Text;
TimerLabel.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
private void Delete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you wish to delete.", "Removing User", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
listView1.Items.Clear();
timer1.Stop();
}
}
This is what i used for the update function and delete row function.
private void updatebutton()
{
CSession updatedsession = new CSession();
int updateindex = 0;
int index = 0;
foreach (CSession lookup in sessionlist)
{
if(lookup.password == PasswordText.Text)
{
if (MessageBox.Show("Do you wish to add time.", "Adding Time",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
updatedsession = lookup;
updateindex = index;
}
break;
}
index++;
}
updatedsession.purchased_time = workingTimeSpan +
updatedsession.purchased_time;
updatedsession.remaining_time = workingTimeSpan +
updatedsession.remaining_time;
sessionlist[updateindex] = updatedsession;
//sortedSessionList[PasswordText.Text] = updatedsession;
PasswordText.Text = "";
TimerLabel.Text = "";
workingTimeSpan = new TimeSpan();
}
private void Update_Click(object sender, EventArgs e)
{
updatebutton();
}
private void Delete_Click(object sender, EventArgs e)
{
CSession cSession = new CSession();
if (MessageBox.Show("Do you wish to delete.", "Removing User",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
int index = 0;
foreach (CSession c in sessionlist)
{
if(c.password == PasswordText.Text)
{
break;
}
index++;
}
sessionlist.RemoveAt(index);
}
}

Create a HaarCascade to output percentages instead of outputting a "true" when a threshold is being surpassed

My goal is to use my webcam to capture my face and detect my mood by facial expression. The output should be probabilites like 70 % happy, 10 % sad, ...
My approach: very happy and very sad ( and other states ) faces should be saved in a HaarCascade.
My problems are twofold:
How do I create a HaarCascade to use with HaarObjectDetector for the
HaarObjectDetector object to output percentages instead of
outputting a "true" when a threshold is being surpassed?
How do I create a HaarCascade for HaarCascade? Is it easier to use String path = #"C:\Users\haarcascade-frontalface_alt2.xml"; HaarCascade cascade1 = HaarCascade.FromXml(path); with opencv-xml or generate it using HaarCascade m = new HaarCascade(20,20,HaarCascadeStages);? What would HaarCascadeStages be?
Have others already solved this issue and offer sourcecode for c#?
My current code:
public partial class Form1 : Form
{
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
Bitmap picture;
HaarObjectDetector detector;
FaceHaarCascade cascade;
public Form1()
{
InitializeComponent();
}
// get the devices name
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox1.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No capture device on your system");
}
}
//toggle start and stop button
private void start_Click(object sender, EventArgs e)
{
}
//eventhandler if new frame is ready
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
picture = (Bitmap)eventArgs.Frame.Clone();
//Rectangle[] objects = detector.ProcessFrame(picture);
//if (objects.Length > 0)
//{
// RectanglesMarker marker = new RectanglesMarker(objects, Color.Fuchsia);
// pictureBox1.Image = marker.Apply(picture);
//}
pictureBox1.Image = picture;
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
}
//prevent sudden close while device is running
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
private void Form1_Load(object sender, EventArgs e)
{
getCamList();
cascade = new FaceHaarCascade();
detector = new HaarObjectDetector(cascade, 30);
detector.SearchMode = ObjectDetectorSearchMode.Average;
detector.ScalingFactor = 1.5f;
detector.ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller;
detector.UseParallelProcessing = false;
detector.Suppression = 2;
}
private void rfsh_Click_1(object sender, EventArgs e)
{
}
private void start_Click_1(object sender, EventArgs e)
{
if (start.Text == "Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(640, 480);
//videoSource.DesiredFrameRate = 10;
videoSource.Start();
label2.Text = "Device running...";
start.Text = "Stop";
timer1.Enabled = true;
}
else
{
label2.Text = "Error: No Device selected.";
}
}
else
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
label2.Text = "Device stopped.";
start.Text = "Start";
}
}
}
}

Audio playing stopped when i resize a WaveForm to form size

I have a problem with my audio application. I'm using nAudio library.
So when I play a sound without using "SamplesPerPixel" method on my waveViewer control, everything works perfectly, but when I want assign a value to this method. The Sound, when I play it starts from unexpected time and finish about 4sec. later.
Here is my code:
namespace AudioMixer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int bytesPerSample;
int samples;
int samplespixel;
private NAudio.Wave.WaveStream pcm = null;
private NAudio.Wave.BlockAlignReductionStream stream = null;
private NAudio.Wave.DirectSoundOut output = null;
private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Audio File (*.wav;*.mp3)|*.wav;*.mp3;";
if (dialog.ShowDialog() != DialogResult.OK) return;
DisposeWave();
if (dialog.FileName.EndsWith(".mp3"))
{
pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else if (dialog.FileName.EndsWith(".wav"))
{
pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
output = new NAudio.Wave.DirectSoundOut();
output.Init(stream);
output.Stop();
waveViewer1.WaveStream = stream;
bytesPerSample = (pcm.WaveFormat.BitsPerSample / 8) * pcm.WaveFormat.Channels;
samples = (int)(pcm.Length / bytesPerSample);
samplespixel = samples / this.Width;
waveViewer1.SamplesPerPixel = samplespixel;
opened_file_name.Text = dialog.FileName;
play_button.Visible = true;
play_button.Enabled = true;
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
waveViewer1.SamplesPerPixel = samplespixel;
}
private void Form1_Load(object sender, EventArgs e)
{
opened_file_name.Text = "Audio file not opened, choose one from Your computer";
play_button.Visible = false;
}
private void play_button_Click(object sender, EventArgs e)
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Pause();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
{
output.Play();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Stopped)
{
output.Play();
}
}
}
private void DisposeWave()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Stop();
output.Dispose();
output = null;
}
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DisposeWave();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
i think this may help you
waveViewer1.SamplesPerPixel = 400;
waveViewer1.StartPosition = 400;

ADD url in textbox to listbox in Windows Form Application c#

Iam new in programming.In windows Form application ,I want user can write a url in textbox and add (with button) in listbox as a favorite list,then user can click in listbox and then go to browser, finaly can save and open the list? whitout Microsoft Sql Database.I Need a source code.
textbox: (Enter your WebSite) : www.google.com
Button:ADD To List Box
Listbox:WWW.Google.com
Button :Save
Button :Open
You have to save the ListBox.Items as plain text file if not wanting to use database. Without binding, this simple problem becomes a little nasty if you start digging into writing it. Here is one of the solution you may need:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int lastIndex = -1;
bool suppressSelectedIndexChanged;
//Click event handler for buttonAdd
private void buttonAdd_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
suppressSelectedIndexChanged = true;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
suppressSelectedIndexChanged = false;
}
//Click event handler for buttonRemove
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndices.Count == 0) return;
int k = listBox1.SelectedIndices[0];
suppressSelectedIndexChanged = true;
for (int i = listBox1.SelectedIndices.Count - 1; i >= 0; i--)
listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
suppressSelectedIndexChanged = false;
lastIndex = -1;
listBox1.SelectedIndex = k < listBox1.Items.Count ? k : listBox1.Items.Count - 1;
if (listBox1.Items.Count == 0) textBox1.Clear();
}
//Click event handler for buttonSave
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "URLs file|*.urls";
save.FileOk += (s, ev) =>
{
using (StreamWriter writer = File.CreateText(save.FileName))
{
foreach (object item in listBox1.Items)
{
writer.WriteLine(item.ToString());
}
}
};
save.ShowDialog();
}
//Click event handler for buttonOpen
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "URLs file|*.urls";
open.FileOk += (s, ev) =>
{
listBox1.Items.Clear();
using (StreamReader reader = File.OpenText(open.FileName))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
};
open.ShowDialog();
}
//SelectedIndexChanged event handler for listBox1
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (suppressSelectedIndexChanged) return;
if (lastIndex > -1)
{
listBox1.Items[lastIndex] = textBox1.Text;
}
lastIndex = listBox1.SelectedIndex;
if (listBox1.SelectedIndex > -1)
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
}
//Click event handler for buttonVisit
private void buttonVisit_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem == null) return;
System.Diagnostics.Process.Start(listBox1.SelectedItem.ToString());
}
}
Here is the GUI screen shot for you to know which controls are needed:
private void btnAdd_Click(object sender, EventArgs e)
{
string _webstring = #"http://";
string _website = _webstring + textBox1.Text;
listBox1.Items.Add(_website);
using (StreamWriter w = File.AppendText("websites.txt"))
{
WriteLog(_website, w);
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
private void btnLaunch_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("iexplore.exe", listBox1.SelectedItem.ToString());
}
private void btnSave_Click(object sender, EventArgs e)
{
using (StreamWriter w = File.AppendText("websites.txt"))
{
foreach (string items in listBox1.Items)
{
WriteLog(items, w);
}
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
public static void WriteLog(string logMessage, TextWriter w)
{
w.WriteLine(logMessage, logMessage);
}
public static void DisposeLog(StreamReader r)
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
private void btnRetrieve_Click(object sender, EventArgs e)
{
using (TextReader txtRead = File.OpenText("Websites.txt"))
{
string _text = "";
string[] _textArray = null;
while ((_text = txtRead.ReadLine()) != null)
{
_textArray = _text.Split('\t');
listBox1.Items.Add(txtRead.ReadLine());
}
txtRead.Close();
}
}
hope this helps.. thanks

Need help getting listbox item text from secondary form to main form

I have been looking all over the Internet for this and have found similar, but none of it will work for me. Everything I have found assumes the listbox is on the main form and not the secondary form, or the code is for an older version of C# or Visual Studio (I am using VS2008).
I am creating a web browser that has a button on the main form (called frmMyBrowser) to open a dialog (frmBookmarks) with a listbox (lstBookmark) with bookmarked URLs. I need to be able to double click on an item (the bookmarked URL) and have the text pasted into the address bar (cmbAddress) of the main form.
Any help would be GREATLY appreciated.
I figured out that if I create the window at runtime, I can get it to work. In case anyone is interested, the code I used is below.
public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
frmFavorites.ShowIcon = false;
frmFavorites.ShowInTaskbar = false;
frmFavorites.MinimizeBox = false;
frmFavorites.MaximizeBox = false;
frmFavorites.ControlBox = false;
frmFavorites.Text = "Bookmarks";
frmFavorites.Width = 500;
frmFavorites.Height = 350;
frmFavorites.Controls.Add(lstFavorites);
frmFavorites.Controls.Add(btnRemoveFavorite);
frmFavorites.Controls.Add(btnAddFavorite);
frmFavorites.Controls.Add(btnCloseFavorites);
frmFavorites.Controls.Add(txtCurrentUrl);
lstFavorites.Width = 484;
lstFavorites.Height = 245;
btnRemoveFavorite.Location = new Point(8, 280);
btnAddFavorite.Location = new Point(8, 255);
btnCloseFavorites.Location = new Point(400, 255);
txtCurrentUrl.Location = new Point(110, 255);
txtCurrentUrl.Size = new Size(255, 20);
btnAddFavorite.Text = "Add";
btnRemoveFavorite.Text = "Remove";
btnCloseFavorites.Text = "Close";
txtCurrentUrl.Text = wbBrowser.Url.ToString();
btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
frmFavorites.Load += new EventHandler(frmFavorites_Load);
btnCloseFavorites.Click += new EventHandler(btnCloseFavorites_Click);
lstFavorites.MouseDoubleClick += new MouseEventHandler(lstFavorites_MouseDoubleClick);
frmFavorites.Show();
}
public void btnCloseFavorites_Click(object sender, EventArgs e)
{
if (lstFavorites.Items.Count > 0)
{
using (StreamWriter writer = new System.IO.StreamWriter(#Application.StartupPath + "\\favorites.txt"))
{
for (int i = 0; i < lstFavorites.Items.Count; i++)
{
writer.WriteLine(lstFavorites.Items[i].ToString());
}
writer.Close();
}
}
frmFavorites.Hide();
}
public void btnAddFavorite_Click(object sender, EventArgs e)
{
string strFavoriteAddress = wbBrowser.Url.ToString();
if (!lstFavorites.Items.Contains(strFavoriteAddress))
{
lstFavorites.Items.Add(strFavoriteAddress);
MessageBox.Show("Favorite Added", "Message");
}
else if (lstFavorites.Items.Contains(strFavoriteAddress))
{
MessageBox.Show("This site already exists in your Favorites list!", "Error");
}
else
{
}
}
public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
try
{
lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
}
catch
{
MessageBox.Show("You need to select an item", "Error");
}
}
public void frmFavorites_Load(object sender, EventArgs e)
{
try
{
using (StreamReader reader = new System.IO.StreamReader(#Application.StartupPath + "\\favorites.txt"))
{
while (!reader.EndOfStream)
{
for (int i = 0; i < 4; i++)
{
string strListItem = reader.ReadLine();
if (!String.IsNullOrEmpty(strListItem))
{
lstFavorites.Items.Add(strListItem);
}
}
}
reader.Close();
}
}
catch
{
MessageBox.Show("An error has occured", "Error");
}
}
private void lstFavorites_MouseDoubleClick(object sender, MouseEventArgs e)
{
string strSelectedAddress = lstFavorites.Text.ToString();
cmbAddress.Text = strSelectedAddress;
wbBrowser.Navigate(strSelectedAddress);
frmFavorites.Hide();
}

Categories

Resources