c# listbox - first selected item is played - c#

Here is my problem: I have a TextBox, button, and a ListBox. The functions works right but whenever I search flash videos, the moment I click the search button, the first video on the list is played. I don't want it to be played on that time - I want to choose from the list without playing the first highlighted item on the ListBox.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
var path = "C:\\Users\\John\\Desktop\\Video\\FLASH";
listBox1.DataSource = Directory.GetFiles(path, "*" + txtbox1.Text + "*")
.Select(f => Path.GetFileName(f))
.ToList();
}
This is the search button. It will search the text on textbox1 from the specified path:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
var fileName = listBox1.SelectedItem as string;
if (fileName != null)
{
var path = Path.Combine("C:\\Users\\John\\Desktop\\Video\\FLASH", fileName);
Process.Start(path);
}
}
This is the ListBox, the searched items will be here, but there is always one item selected and that item plays whenever the search finished.

Fill the list, then add the selectedindexchanged event handler. (Make sure that the event isn't added for you by the designer).
So,
listBox1.DataSource = ...
listBox1.SelectedIndexChanged +=
new System.EventHandler(this.listBox1_SelectedIndexChanged);

Related

C# WinForms contextmenu focus issue when textbox is added

In a C# WinForms application I need to create a ContextMenuStrip with dropdown and textbox:
private System.Windows.Forms.ContextMenuStrip ct1;
private void button_Click(object sender, EventArgs e)
{
var header = new ToolStripMenuItem("Header");
header.Enabled = false;
var options = new ToolStripMenuItem("Options");
for (int i = 0; i < 5; i++)
{
var checkoption = new ToolStripMenuItem("Check Me " + i + "!");
checkoption.CheckOnClick = true;
options.DropDownItems.Add(checkoption);
}
var txt = new ToolStripTextBox();
txt.Text = "changeme";
options.DropDownItems.Add(txt);
options.DropDown.Closing += DropDown_Closing;
ct1.Items.Clear();
ct1.Items.Add(header);
ct1.Items.Add(options);
ct1.Show(this, button.Left, button.Top);
}
private void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
e.Cancel = (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked);
}
Now, e.Cancel will prevent closing the dropdown if the reason is ItemClicked, so I can select more items without having to open the menu again:
Please note that "changeme" is a ToolStripTextBox!
Once I focus it (click on it), I can edit the text inside:
After finish editing the textbox, I still can change the checkbox items, but there is no focus indicator:
How can I get back the focus indicator just as shown on the first picure?
Note: if I move the mouse onto "Header", the dropdown will close, and then moving it back to "Options", will reopen the dropdown and then the focus indicator is good again:
How can I do this without closing and reopening the dropdown?
I have tried Select() for the options item, but it did not help, neither Invalidate() on ct1.
Just have found it:
First needs to add a click handler on the dropdown:
options.DropDown.Click += DropDown_Click;
Then in the click handler it needs to be focused:
private void DropDown_Click(object sender, EventArgs e)
{
var dropdown = (ToolStripDropDown)sender;
dropdown.Focus();
}

Calling a method when a listview item is focused C#

I am making a small C# application where the user enters information. the information is stored in an object and the object is in turn stored in a list. The information is displayed to the user in a listview.
I want to make it so that when the user clicks on an item in the listview the index of that item is passed to the list which finds the object with the same index and gets its information. The information is then shown in the same textboxes that the user enters his or hers information in.
My problem is that i do not now what method to call when the user selects a row in the listview.
This is what i have:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 1)
{
index = listView1.FocusedItem.Index;
textBox1.Text = manager.FocusedContact(index).FirstName;
textBox2.Text = manager.FocusedContact(index).LastName;
textBox3.Text = manager.FocusedContact(index).Street;
textBox4.Text = manager.FocusedContact(index).City;
textBox5.Text = manager.FocusedContact(index).ZipCode;
}
}
i tried:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
textbox1.Text = "hi";
}
so i know that private void listView1_SelectedIndexChanged is the wrong method, or is there some option for the listview that i forgot to toggle on or off?
You should be able to retrieve the selected index like this:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
var index = listView1.SelectedIndex;
}
If the event is not firing at all, check that the event handler is registered correctly in the form's Designer.cs file. In your case, it should look like this:
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);

Drag multiple files

I have a ListBox with a list of filepaths, which has the property SelectionMode set to MultiExtended. Thus, I can select many items from this list.
Now, I want to Drag and Drop files starting from those paths in the destination folder where I drop them.
My code:
private void Form1_Load(object sender, EventArgs e)
{
// populate the FileList
// i.e. FileList.Items.Add("d:/Samples/file-00" + i + ".wav");
this.FileList.MouseDown += new MouseEventHandler(FileList_MouseDown);
this.FileList.DragOver += new DragEventHandler(FileList_DragOver);
}
void FileList_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
void FileList_MouseDown(object sender, MouseEventArgs e)
{
List<string> filesToDrag = new List<string>();
foreach (var item in FileList.SelectedItems)
{
filesToDrag.Add(item.ToString().Trim());
}
this.FileList.DoDragDrop(new DataObject(DataFormats.FileDrop,
filesToDrag.ToArray()), DragDropEffects.Copy);
}
it works perfect if I select and drop 1 single line/file from the ListBox to the destination folder.
Instead, if I do a multiple selection and I try to drag and drop, it can just select that one line where I start to drag. Seems that MouseDown prevent this?
How would you fix the problem?
Doing this with a ListBox seems to be ridiculously hard. Actually I haven't found a solution at all..
Use a ListView instead! It is easy as pie, using the ItemDrag event and is a much better control anyway.. I can't count how often I had to change from a 'cheap' ListBox to ListView because I needed this or that 'little' extra..
Here is your code moved to a ItemDrag:
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
List<string> filesToDrag = new List<string>();
foreach (var item in listView1.SelectedItems)
{
filesToDrag.Add(item.ToString().Trim());
}
this.listView1.DoDragDrop(new DataObject(DataFormats.FileDrop,
filesToDrag.ToArray()), DragDropEffects.Copy);
}
Note that this only solves the problem of the MouseDown changing the selection. It is in itself not a guarantuee that the actual copying will work.
I found this interesting article that proposes a solution. Maybe you don't need it, as you have said that you got copying one file already working..
Yeah...I don't think there's a good way around that problem. When you click again to initiate the drag it will toggle that item. We don't know that the user actually wants to do a drag until the mouse is held down and moved.
One potential solution is to initiate the drag/drop from something else, just somehow make it really clear that is what the user should drag. Here I'm using a Label instead of the ListBox:
void label1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
List<string> filesToDrag = new List<string>();
foreach (var item in FileList.SelectedItems)
{
filesToDrag.Add(item.ToString().Trim());
}
if (filesToDrag.Count > 0)
{
this.FileList.DoDragDrop(new DataObject(DataFormats.FileDrop,
filesToDrag.ToArray()), DragDropEffects.Copy);
}
else
{
MessageBox.Show("Select Files First!");
}
}
}
You have to be picky about the mouse down and mouse move activities. When it is within the graphics rectangle of your listbox, you'll want normal behavior. When it is outside the bounds of this rectangle, you'll want drag/drop functionality. You can try the pseudo code below:
MouseDown(sender, e)
{
var x = <your sender as control>.ItemFromPoint(.....)
this.mouseLocation = x == null ? x : e.Location;
}
MouseMove(sender, e)
{
if control rectangle doesn't contain the current location then
<your sender as control>.Capture = false
DoDragDrop
}

How to bind suggestions with text box with first and last name?

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...

open and save file dialog

i use an openFileDialog to read from a text file and print the values in a listbox and a saveFileDialog to save the changes in textfile.i wrote this code but it doesn't work.if a change the listbox with a textbox works fine.But i need to print and save the items into a listbox.any suggestions?
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label7.Text = openFileDialog1.FileName;
listBox1.Text = File.ReadAllText(label7.Text);
}
}
private void button5_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, listBox1.Text);
}
}
You need to add each line of the file as a listbox item. Then, to save, loop through each listbox item and write it as a new line.
You can use File.ReadAllLines and listBox1.Items.AddRange to add the items.
listBox1.Items.AddRange(File.ReadAllLines(openFileDialog1.FileName));
Since the Items property contains objects, not strings, you will need to manually loop over the items and write them individually... perhaps doing something like
StringBuilder sb = new StringBuilder();
foreach(object item in listBox1.Items) {
sb.AppendLine(item.ToString();
}
File.WriteAllText(saveFileDialog1.FileName, sb.ToString());
ListBox.Text represents only a selected part of the list box items.
A quote from MSDN docs:
When the value of this property is set to a string value, the ListBox searches for the item within the ListBox that matches the specified text and selects the item. You can also use this property to determine which items are currently selected in the ListBox
This should work :
using System.Linq;
...
string[] lines = File.ReadAllLines(fileName);
listBox.Items.AddRange(lines.ToArray<object>());

Categories