When I click the button the first time, it works, but after that, it doesn't do anything. I have tried to debug this and I have looked it up but I can't find an answer. I am probably just not noticing something obvious.
private void button5_Click(object sender, EventArgs e)
{
string[] files;
files = Directory.GetFiles("Tasks");
foreach (string file in files)
{
string[] lines;
StreamReader reader = new StreamReader(file);
lines = File.ReadAllLines(file);
tasks.Add(lines[0]);
reader.Close();
}
listBox1.DataSource = tasks;
}
You're problem is not with the button. It's with the listbox. It's not updating properly because it's not detecting a change in your datasource.
Try setting it to null before updating so it knows it's changing:
listBox1.DataSource = null;
listBox1.DataSource = tasks;
Alternative Method:
You can also use a BindingList instead of a regular list.
See here:
How to refresh DataSource of a ListBox in C# WinForms
Related
I failed to fill combobox with csv filenames. I created the combobox by dragging from toolbox in Microsoft Visual Studio. I set the name of combobox to ChooseSampleSheet.
The following is my code:
private void ChooseSampleSheet_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryInfo d = new DirectoryInfo(#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.csv"); //Getting Text files
ChooseSampleSheet.DataSource = Files;
ChooseSampleSheet.DisplayMember = "Name";
}
Also, I tried the following code:
private string path = (#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");
private void ChooseSampleSheet_SelectedIndexChanged(object sender, EventArgs e)
{
List<String> Configurations = Directory.EnumerateDirectories(path, "*.exe")
.Select(p => Path.GetFileName(p))
.ToList();
ChooseSampleSheet.DataSource = Configurations;
}
But Neither of them works. Nothing shows in my combobox. I expected to see csv file names. So that I can click to open selected file afterwards (not show in in my code).
People suggested me to change the event. The following is my update.
private void form4_load(object sender, EventArgs e)
{
DirectoryInfo d = new DirectoryInfo(#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.csv"); //Getting Text files
ChooseSampleSheet.DataSource = Files;
ChooseSampleSheet.DisplayMember = "Name";
}
private void ChooseSampleSheet_SelectedIndexChanged(object sender, EventArgs e)
{
}
However, nothing show in the combobox still.
I do not see anything wrong in your code however I think your code is at the wrong place.
SelectedIndexChanged will get execute when you select something from the drop down. Since your drop down has not been filled with values , you can't fire that event.
Put the same code in form_load and you will see the values there.
DirectoryInfo d = new DirectoryInfo(#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.csv"); //Getting Text files
ChooseSampleSheet.DataSource = Files;
ChooseSampleSheet.DisplayMember = "Name";
I am trying to create a window program where the program reads from a text file and display the data in a listbox. I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat.
How do I do it so that it reads the file and only include new input data?
private void Button_Click(object sender, RoutedEventArgs e)
{
using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Listbox1.Items.Add(line);
}
sr.Close();
}
}
The probably most simple way to do what you want is to read all lines from the file into a collection, and then assign that collection to the ItemsSource property of your ListBox:
private void Button_Click(object sender, RoutedEventArgs e)
{
Listbox1.ItemsSource = File.ReadAllLines(#"C:\Users\jason\Desktop\Outbound.txt");
}
As Clemens said in comment, you can either Listbox1.Items.Clear() or Listbox1.ItemsSource = File.ReadAllLines(#"C:\Users\jason\Desktop\Outbound.txt");
But this would always replace all your listbox with the file. If you just want, as you said, to enter new data, you could simply check if if(!Listbox1.Items.Contains(line)) before adding the item.
Depends on what you really want, reupdate the whole list or just add new entries and not removing old ones.
I have a listView of items, in which the user can only select one at a time. I have the following code, that only works properly when I put it in a try/catch block. The problem is, that some of the item names are too long, and they cause a lot of white space for the other items. Clicking on the white space will cause an ArgumentOutOfRangeException, even though it is in the same row as an item. I solved this by shoving it in a try/catch block, but I feel this is a dirty way of doing it, even if it works. Below is the code.
private void listView1_DoubleClick(object sender, EventArgs e)
{
try
{
string[] arr1 = File.ReadAllLines(listView1.SelectedItems[0].Tag.ToString());
string[] arr2 = arr1[0].Split(';');
}
catch
{
//no catch
}
}
I would like to avoid this altogether, but I do not know how to change the code to make it work without the try/catch. I tried if(!String.IsNullOrEmpty), but it still doesn't work. What is the solution here?
Since your ListView is in View=List selecting makes it necessary to hit the item text.
This is inconvenient I have to admit and turnnig on FullRowSelect doesn't help, as it is only for View=Details.
Here is a quick fix:
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
var hit = listView1.HitTest(e.Location);
if (hit.Item != null)
{
string file = hit.Item.Text;
string[] arr1 = null;
if (File.Exists(file)) arr1 = File.ReadLines(file).ToArray();
...
}
}
You may instead want to go to the bottom of the issue and add code to the MouseUp event to select the row..:
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
var hit = listView1.HitTest(e.Location);
if (hit.Item != null) hit.Item.Selected = true;
}
Note that the HitTest will only catch Items, empty or not, not really emtpy background space to the right or bottom..!
IDE: C#.net, Winforms, .net 4.0
I want to bind a text box with suggestions, suggestions will come from a list, that list is having space separated words for example 'Little Jhon' now with the help of following code I have implemented suggestion functionality, but I want when user type anything suggestions should come from both words, currently it is coming from first word only.
Code:
private void BindTournamentNames()
{
//On Load Code
List<String> lstNames= new List<string>();
lstNames.Add("Little John");
lstNames.Add("Hello Yogesh");
var source = new AutoCompleteStringCollection();
txtBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
source.AddRange(lstNames.ToArray());
txtBox1.AutoCompleteCustomSource = source;
txtBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
Now when I am typing in textBox 'Little' it is giving me suggestion, but when I am typing John it is not giving me suggestion, please tell me how to do this.
Well existing autoComplete functionality only supports searching by prefix. I have the same requirement in one of my project. So what i had done is -
Added a ListBox just below the TextBox and set its default visibility to false. Then use the OnTextChanged event of the TextBox and the SelectedIndexChanged event of the ListBox to display and select the items. like this -
Note: Assume your BindTournamentNames() method called in Form's constructor.
protected void textBox1_TextChanged(object sender, System.EventArgs e)
{
listBox1.Items.Clear();
if (textBox1.Text.Length == 0)
{
listBox1.Visible = false;
return;
}
foreach (String s in textBox1.AutoCompleteCustomSource)
{
if (s.Contains(textBox1.Text))
{
listBox1.Items.Add(s);
listBox1.Visible = true;
}
}
}
protected void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
listBox1.Visible = false;
}
good luck...
I intend to create a .mp4 Listbox from which I can play an .mp4 of my choice.
I've already created the .mp4 player(by drag&drop) and I'm dealing with trouble with how to deal with the listBox.
private void button1_Click(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
try
{
DirectoryInfo dr = new DirectoryInfo(dialog.SelectedPath.ToString());
if (result == FORMS.DialogResult.OK)
{
foreach (FileInfo f in dr.GetFiles())
{
listBox1.Items.Add(f);
}
}
}
catch { }
}
This only enables me to get all the .mp4 files(from selected folder) to be shown in the listBox,
How do I manage to drag objects from the listBox into the .mp4 player(which is already drag and drop enabled).
You can do it using the DragDrop.DoDragDrop method.
Example:
<ListBox SelectionChanged="Selector_OnSelectionChanged">
<ListBoxItem>X</ListBoxItem>
<ListBoxItem>Y</ListBoxItem>
<ListBoxItem>Z</ListBoxItem>
</ListBox>
And in code
private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listbox = sender as ListBox;
DragDrop.DoDragDrop(listbox, listbox.SelectedItem, DragDropEffects.None);
}
Could be that in your mp4 player you'll need to implement more than just enable drag&Drop (like extract dragged item and play it ...)
You can find more information about on MSDN Drag and Drop Overview page.
Hope this helps
:) Thanks alot, that really helps! You were right about the .mp4 player, he does need to identify the drag onto him but I just couldn't figure out how. I did manage to write the code to play an .mp4 by dragging an .mp4 directly from your computer (desktop for example) and here's the code for that:
private void Grid_Drop(object sender, DragEventArgs e)
{
string filename = (string)((DataObject)e.Data).GetFileDropList()[0];
mediaElement1.Source =new Uri(filename);
mediaElement1.LoadedBehavior = MediaState.Manual;
mediaElement1.UnloadedBehavior = MediaState.Manual;
mediaElement1.Volume = (double)slider_vol.Value;
mediaElement1.Play();
}
There are other add-ons to that code but they don't really matter.
What function from Drag and Drop should I use on the "Play" button for the player? and how do I get the filename to actually handle that file? Thanks!