I got a Form that wants to have atleast one keyword, like download.
This is the Code to call my OpenFileDialog.
The Class is Form1
public Form1()
{
InitializeComponent();
initListView();
}
private void button1_Click(object sender, EventArgs e)
{
getallfiles.getSelectedFiles(this.listView1);
}
private void initListView()
{
listView1.View = View.Details;
listView1.Columns.Add("Filename", 210, HorizontalAlignment.Left);
listView1.Columns.Add("Size", 60, HorizontalAlignment.Left);
listView1.Columns.Add("Match", 60, HorizontalAlignment.Left);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
listView1.Items.Clear();
seaching.matchResult(progressBar1, listView1, textBox1.Text, textBox2.Text);
}
catch (Exception f)
{
MessageBox.Show(f.ToString());
}
}
Now I get the Multiselected Files and store them in the filePaths String[].
The Class is getallfiles
public static String[] filePaths;
public static void getSelectedFiles(ListView listView)
{
OpenFileDialog openAllFiles = new OpenFileDialog();
openAllFiles.Title = "Select all files you want to look for keywords";
openAllFiles.Multiselect = true;
openAllFiles.Filter = "(*.*)|*.*";
if (openAllFiles.ShowDialog() == DialogResult.OK)
{
filePaths = new string[openAllFiles.FileNames.Length];
int count = 0;
foreach (String file in openAllFiles.FileNames)
{
try
{
ListViewItem masterItem = new ListViewItem(new[] { Path.GetFileName(file), (Math.Round(((new FileInfo(file).Length) / 1024f), 3).ToString()) + " kb"});
listView.Items.Add(masterItem);
filePaths[count] = file;
count++;
}
catch (Exception f)
{
MessageBox.Show(f.ToString());
}
}
}
}
And now my Problemcode. I can filter if there is only the Keyword written, but if it's downloading and I set the Keyword to download my solutions stops working.
The Class is searching
public static void matchResult(ProgressBar progressBar, ListView listView, String key1, String key2)
{
progressBar.Maximum = getallfiles.filePaths.Length;
progressBar.Value = 0;
int count = 0;
bool lockCount = false;
String fileText;
foreach (string file in getallfiles.filePaths)
{
using (StreamReader reader = new StreamReader(getallfiles.filePaths[count]))
{
while ((fileText = reader.ReadLine()) != null)
{
if (String.IsNullOrEmpty(key2) & !String.IsNullOrEmpty(key1))
{
if (fileText.Contains(key1.ToLower()) | fileText.Contains(key1.ToUpper()) | fileText.Contains(key1))
{
ListViewItem masterItem = new ListViewItem(new[] { Path.GetFileName(file), (Math.Round(((new FileInfo(file).Length) / 1024f), 3).ToString()) + " kb" });
listView.Items.Add(masterItem);
count++;
lockCount = true;
reader.Close();
break;
}
}
else if(!String.IsNullOrEmpty(key2))
{
if (fileText.Contains(key1.ToLower()) | fileText.Contains(key2.ToLower()) | fileText.Contains(key1.ToUpper()) | fileText.Contains(key2.ToUpper()) | fileText.Contains(key1) | fileText.Contains(key2))
{
ListViewItem masterItem = new ListViewItem(new[] { Path.GetFileName(file), (Math.Round(((new FileInfo(file).Length) / 1024f), 3).ToString()) + " kb" });
listView.Items.Add(masterItem);
count++;
lockCount = true;
reader.Close();
break;
}
}
}
if (!lockCount)
{
count++;
}
}
}
}
My next Idea was to check for a Char[] but I'm not sure if this is efficient.
I'd let read char for char and store the current line in a char[] and compare if the char[] I'm looking for is in there.
Related
I am practicing an OCR program using C#, I am not much of a coder so I am trying to find my way around.
1- I OCR some pdf files.
2- I see the output of the OCR.
3- I use UI buttons to browse and then click convert.
4- I have a progress bar on the UI but it does not visually upgrade, while when I log the progressBar.Value I see its numbers are updating.
So I searched around and I found that the issue is I should like stop the thread and create a new one for the Ui to visually update, but I really do not understand that, or even do not know how to do it.
Can someone please help me ? like baby steps.
Also I know I have copied and pasted like alot of code for you to see.
The case is the following:
1- class fmMain: Form has a progressBarIncrementation function, responsible for taking the increment value from a function in processFunctions class.
2- progressBarIncrementation function has progressBar.Value to be updated, I see its value updated.
3- But visually nothing is updated. I tried some threading code, but i do not understand it so.....
class processFunctions
{
Thread newThread = Thread.CurrentThread;
private string invoiceNameIndex = "";
private string invoiceIBANIndex = "";
private string invoiceNumberIndex = "";
private string invoiceDateIndex = "";
private string invoiceSubtotalIndex = "";
private string invoiceVATIndex = "";
private string invoiceTotalIndex = "";
private string[] filePath;
private string[] fileNamePDF;
private int totalNumberOfFiles;
private string InformationNeeded(string wholeRead, string ix)
{
string[] lines = wholeRead.Split(new[] { "\r\n", "\r", "\n", " " }, StringSplitOptions.None);
if(ix.Contains(","))
{
string[] variableIndex = ix.Split(',');
string name = "";
for(int i =0; i < variableIndex.Length; i++)
{
name += lines[Convert.ToInt32(variableIndex[i])];
}
return name;
}
return lines[Convert.ToInt32(ix)];
}
public void ocrFunction(string filePathOnly)
{
var Ocr = new AutoOcr();
var Results = Ocr.ReadPdf(filePathOnly);
var Barcodes = Results.Barcodes;
var Text = Results.Text;
string[] numbers = { invoiceNameIndex, invoiceIBANIndex, invoiceNumberIndex,
invoiceDateIndex, invoiceSubtotalIndex, invoiceVATIndex, invoiceTotalIndex};
string[] results = new string[numbers.Count()];
for (int i = 0; i < numbers.Length; i++)
{
results[i] = InformationNeeded(Text, numbers[i]);
Console.WriteLine(results[i]);
}
Results = null;
Ocr = null;
Barcodes = null;
Text = null;
}
public int browseFile()
{
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}
public void databaseReader()
{
string connectionString;
SqlConnection connection;
connectionString = ConfigurationManager.ConnectionStrings["OCR_App.Properties.Settings.LibraryConnectionString"].ConnectionString;
for (int i = 0; i < fileNamePDF.Length; i++)
{
string fileNameFiltered = fileNamePDF[i].Replace(".pdf", "");
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM invoicesTable WHERE invoiceRef = '" + fileNameFiltered + "'", connection))
{
DataTable invoicesTable = new DataTable();
adapter.Fill(invoicesTable);
DataRow index = invoicesTable.Rows[0];
invoiceNameIndex = (index[1].ToString());
invoiceIBANIndex = (index[2].ToString());
invoiceNumberIndex = (index[3].ToString());
invoiceDateIndex = (index[4].ToString());
invoiceSubtotalIndex = (index[5].ToString());
invoiceVATIndex = (index[6].ToString());
invoiceTotalIndex = (index[7].ToString());
ocrFunction(filePath[i]);
//newThread.Start();
fmMain formFunctions = new fmMain();
//Thread.Yield();
//Thread thread = new Thread(() => formFunctions.ProgressBarIncrementation(progressBarIncrement()));
formFunctions.ProgressBarIncrementation(progressBarIncrement());
}
}
}
public int progressBarIncrement()
{
int incrementValue = 0;
incrementValue = incrementValue + 100 / totalNumberOfFiles;
//Console.WriteLine(incrementValue);
return incrementValue;
}
///////////////////////////////////////////////////////////////////
public partial class fmMain : Form
{
processFunctions processingMain = new processFunctions();
ProgressBar NewprogressBar = new ProgressBar();
private static int incrementbar = 0;
public fmMain()
{
InitializeComponent();
}
[STAThread]
private void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = processingMain.browseFile();
txtBoxFilePath.Text = number.ToString();
}
public void BtnConvert_Click(object sender, EventArgs e)
{
processingMain.databaseReader();
}
private void fmMain_Load(object sender, EventArgs e)
{
}
private void txtBoxFilePath_TextChanged(object sender, EventArgs e)
{
}
private void NumberOfFilesToBeProcessed_Click(object sender,
EventArgs e)
{
}
public void progressBar_Click(object sender, EventArgs e)
{
progressBar.Maximum = 100;
NewprogressBar.Value = progressBar.Value;
}
public void ProgressBarIncrementation(int incrementValue)
{
//Thread.Yield();
//Thread newThread = Thread.CurrentThread;
incrementbar = incrementbar + incrementValue;
progressBar.Visible = true;
progressBar.Value += incrementbar;
Thread thread = new Thread(() => progressBar.Value += incrementbar);
Console.WriteLine(progressBar.Value);
//progressBar.Value += incrementbar;
}
}
If you are needing the progress bar, you might want to consider creating an event to help report progress to your calling application. And you'll want to mark your function browseFile as async and do the following:
public async Task<int> browseFileAsync()
{
await Task.Run(new Action(() => {
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}));
}
And then in your calling application do:
private async void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = await processMain.browseFileAsync();
txtBoxFilePath.Text = number.ToString();
}
I would also consider not calling a folder browser dialog from your class as this couples your class to a specific implementation. Rather, I would browse for the file from the GUI and pass the selected file(s) to the class.
I want to invoke timer in my c# code on button click.It works well in form load event but didn't work in button click.Please help me to fix it.Thank's in advance.
My code is Here:
public partial class Form1 : Form
{
public int TimeTaken;
public Form1()
{
InitializeComponent();
lblFilesCount.Text = lblFoldersCount.Text = "0";
}
private void btnFolderBrowse_Click(object sender, EventArgs e)
{
DialogResult result = fbdFoldersFiles.ShowDialog();
if (result == DialogResult.OK)
{
string[] files = Directory.GetFiles(fbdFoldersFiles.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
txtFolderPath.Text = fbdFoldersFiles.SelectedPath;
}
private void btnDeleteFiles_Click(object sender, EventArgs e)
{
timerDelete.Enabled= true;
string path = fbdFoldersFiles.SelectedPath;
DirectoryInfo dirFirst = new DirectoryInfo(path);
foreach (FileInfo file in dirFirst.GetFiles())
{
timerDelete.Enabled = true;
DateTime dt = File.GetLastWriteTime(file.FullName);
if (dt < dtpDate.Value)
{
DeleteFiles(file);
}
}
string[] dirArray = Directory.GetDirectories(path, "*", SearchOption.AllDirectories).ToArray();
Array.Reverse(dirArray);
foreach (var directory in dirArray)
{
if (Directory.GetFiles(directory).Length > 0 || Directory.GetDirectories(directory).Length>0)
{
DirectoryInfo dir = new DirectoryInfo(directory);
FileInfo[] files = dir.GetFiles().ToArray();
foreach (FileInfo file in files)
{
timerDelete.Enabled = true;
DateTime dt = File.GetLastWriteTime(file.FullName);
if (dt < dtpDate.Value)
{
DeleteFiles(file);
}
}
if (Directory.GetFiles(directory).Length == 0 )
{
dir.Delete(true);
lblFoldersCount.Text = (Convert.ToInt32(lblFoldersCount.Text) + 1).ToString();
}
}
}
timerDelete.Enabled = false;
}
protected void DeleteFiles(FileInfo DeleteFile)
{
dgvDisplayFilesInfo.Rows.Add();
int RowIndex = dgvDisplayFilesInfo.RowCount - 1;
DataGridViewRow r = dgvDisplayFilesInfo.Rows[RowIndex];
r.Cells["dgvColoumnSrNo"].Value = RowIndex+1;
r.Cells["dgvColumnFullName"].Value = DeleteFile.Name;
r.Cells["dgvColumnPath"].Value = DeleteFile.Directory;
DeleteFile.Delete();
lblFilesCount.Text = (Convert.ToInt32(lblFilesCount.Text)+1).ToString();
}
private void timerDelete_Tick(object sender, EventArgs e)
{
TimeTaken = TimeTaken++;
lblShowTimeTaken.Text = TimeTaken.ToString();
}
}
First of all you are setting the Enabled=True in the foreach which I don't think it's what you intended. 2nd of all, why don't you use Stopwatch component. It's much easier to use.
Stopwatch sw = new Stopwatch();
sw.Start();
....
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds.ToString())
public static bool loadFileview(Int64 uname,out string[] filename,out string[] extn)
{
bool b = false;
SCPEntities ent = new SCPEntities();
filename = null;
extn = null;
var data = (from n in ent.User_Data where n.Account_Num == uname select new { n.File_Name, n.Extn }).ToList();
int i = 0;
foreach (var v in data)
{
filename[i] = v.File_Name;
extn[i] = v.Extn;
i++;
}
if(liv1!=n)
{
b = true;
// liv = data;
}
return b;
}
}
method call
protected void Page_Load(object sender, EventArgs e)
{
string[] fname;
string[] extn;
Int64 uname = 12121;
bool b = false;
b= home.loadFileview(uname, out fname,out extn);
if (b)
{
for (int count = 0; count <fname.Length; count++)
{
ListViewItem listItem = new ListViewItem(fname[count]);
listItem.SubItems.Add(extn[count]);
FileListView.Items.Add(listItem);
}
}
I want to bind filename & extn to listview control listview11 dynamically, how?
try this:
protected void Page_Load(object sender, EventArgs e)
{
string[] fname;
string[] extn;
Int64 uname = 12121;
bool b = false;
b= home.loadFileview(uname, out fname,out extn);
if (b)
{
for (int count = 0; count <fname.Length; count++)
{
ListViewItem listItem = new ListViewItem (new[] { fname[count], extn[count]})
FileListView.Items.Add(listItem);
}
}
}
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);
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();
}