I want to get Full Path Of Listbox item, because I want to showing all item of ImageListView , Can you give me some idea , If I add A Folder, All Items Of A will show in ImageList View Then it could save setting , Again I add B Folder , All Items Of B will show in ImageList View and save setting.
Thanks in Advance !!
BindingSource listboxsource = null;
public Form1()
{
InitializeComponent();
listboxsource = new BindingSource(Properties.Settings.Default.listboxitems, "");
someListbox.DataSource = listboxsource;
}
//Add Folder in Listbox
private void button57_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "Please Select Folder";
if (dialog.ShowDialog() == DialogResult.OK)
{
string folderName = dialog.SelectedPath;
string s = Path.GetFileName(folderName);
listboxsource.Add(s);
Properties.Settings.Default.Save();
listboxsource = new BindingSource(Properties.Settings.Default.listboxitems, "");
someListbox.DataSource = listboxsource;
}
}
Related
I have created a notepad with a tabbed interface. It is a c# winform application. Now, what I want is this - if the file does not exist anymore, deleted by another program then if I click the related tab, it should show a message that "the file does not exist" and it should close the tab.
private string FolderPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // location of document folder
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.TabCount == 0)
{
return;
}
else
{
TabPage tpp = tabControl1.SelectedTab;
this.FileOnly = tpp.Text + ".txt"; // I used tab names without extension, that's why adding it back
String str = tpp.Text;
string CorrFolderPath = FolderPath.Replace(#"\", #"\\");
string FolderPathcomplete = CorrFolderPath + "\\My_Note\\"; // this is the location of saving files; the folder contents appear as list box entries in the program
string filename = FolderPathcomplete + FileOnly;
if (str.Contains("New Document"))// the new tabs which are not yest saved has the name New Document 1, 2 etc.
{
return;
}
else
{
if (File.Exists(filename))
{
return;
}
else
{
MessageBox.Show("File does not exist! Closing the tab.");
var tabPage = tabControl1.TabPages[str];
tabControl1.TabPages.RemoveByKey(str);
}
}
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage("New Document" + count); //creates a new tab page
tp.Name = "New Document" + count;
RichTextBox rtb = new RichTextBox(); //creates a new richtext box object
tp.Controls.Add(rtb); // adds rich text box to the tab page
tabControl1.TabPages.Add(tp); //adds the tab pages to tab control
tabControl1.SelectedTab = tp;
tabControl1.SelectedIndexChanged += tabControl1_SelectedIndexChanged; // it will check whether tab file exists or not
this.FileName = string.Empty;
count++;
}
Consider using a FileSystemWatcher -- where on creation of a new tab, you create a new watcher and monitor for any changes.
See this article for more information:
https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx
I am creating an application that would load DLLs into a ListBox. It does this by the user pressing a button then the user can open files, and load them into the listview.
So it would look something like this.
The DLL is added in by opening the users files then they add it in themselves and into the ListBox.
My question is. How does I get the exact Path to the MaterialSkin.dll, and put it into a string when someone selected MaterialSkin.dll in the ListBox?
private void materialFlatButton3_Click_1(object sender, EventArgs e) //button used to load the DLL into the ListBox.
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
fullFileName = new List<String>(OpenFileDialog1.FileNames);
// add just the names to the listbox
foreach (string fileName in fullFileName)
{
listBox2.Items.Add(fileName.Substring(fileName.LastIndexOf(#"\") + 1));
}
}
}
If possible I would adjust your OpenFileDialog1 to grab the path when it grabs the file name. Then, using a dictionary instead of a list you can show display member that is just the .dll name, while the value member can be the dir or the dir / .dll name.
Here's what that might look like in the snippet you posted:
private void materialFlatButton3_Click_1(object sender, EventArgs e)
//button used to load the DLL into the ListBox.
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
// ~~Using Dictionary instead of list~~
fullFileName = new Dictionary<string, string>(OpenFileDialog1.FileNames);
// Populate Listbox from dictionary.
listBox2.Datasource = fullFileName.ToList();
listBox2.DisplayMember = "Value";
listBox2.ValueMember = "Key";
}
}
This makes the assumption you can change your OpenFileDialog1 object to return a dictionary instead of a list.
Then you'll just use listBox2.SelectedValue to get the dir.
The exact path comes to you from OpenFileDialog1.FileNames...
So store the full path in a Dictionary with the key corresponding to the current index as you're populating the listBox. When they select an item in the listbox, use that to do your dictionary lookup.
Assuming that this is a WinForms app and not WPF, then you have a couple of options.
if the 'fullFileName' variable is a class variable, then when the user selects an item in the ListBox, you can loop through the full DLL paths in the fullFileName variable until you the matching file name.
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string curItem = listBox1.SelectedItem.ToString();
foreach( var path in fullFileName)
{
if (System.IO.Path.GetFileName(path).Equals(curItem, StringComparison.OrdinalIgnoreCase))
{
MessageBox.Show("Full path = " + path);
break;
}
}
}
Another option is set the DataSource of the ListBox to a list of objects which contain both the DLL name and the full path.Then use the SelectedItemChanged event (not the SelectedIndexChanged) and the SelectedItem will point to the full path.
public class AssemblyItem
{
public string Name {get;set;}
public string FullPath {get;set;}
}
private void materialFlatButton3_Click_1(object sender, EventArgs e)
{
// Use your existing code to get the selection of DLLs
List<AssemblyItem> items = new List<AssemblyItem>();
foreach (string fileName in fullFileName)
{
items.Add(new AssemblyItem()
{
Name = System.IO.Path.GetFileName(fileName),
FullPath = fileName
};
}
listBox1.DataSource = items;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "FullPath";
listBox1.BindData();
}
BTW, I would recommend using the methods in System.IO.Path to get the file names from the path instead of using LastIndexOf.
I am using Windows Application.I Put some data as direct values in combo box.I defined var type to combo box.I put these combo box on form load.Now I want to retrieve the value of selected item on my button2_click event and I tried below code to retrieve it,but it giving me error of The name comboBox does not exist in current context.Can any one suggest me how to fix it.
namespace WinDataStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var daysOfWeek =
new[] { "RED", "GREEN", "BLUE"
};
// Initialize combo box
var comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
// Add the combo box to the form.
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox1.
textBox1.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
//Add file in ListBox.
listBox1.Items.Add(file);
}
}
else
{
// listBox1.Items.Add(String.Format(“No files Found at location:{0}”, textBox1.Text));
}
}
string s = (string)comboBox.SelectedItem;
listBox1.Items.Add(s);
}
}
}
comboBox was local variable in Form1 .ctor. You can't access it from another method
options:
1) access to the control by name
private void button2_Click(object sender, EventArgs e)
{
var comboBox = this.Controls["comboBox"] as ComboBox;
...
}
2) make it a private member of the form as controls normally are, if they are created in designer
ComboBox comboBox;
public Form1()
{
InitializeComponent();
// Initialize combo box
comboBox = new ComboBox() {...};
...
}
Currently the Combobox appears to be a local variable. Try to make it a global field variable and you should be able to access it.
I have two ListBox controls in my application and a button to save it to a text file. But I want to select using a ComboBox which one to save to save in a text file. The following code illustrates what I am trying to do:
private void button4_Click(object sender, EventArgs e)
{
var ss = listBox1.Items;//first listbox
var sb = listBox2.Items;//second listbox
SaveFileDialog svl = new SaveFileDialog();
svl = saveFileDialog1;
svl.Filter = "txt files (*.txt)|*.txt";
if (svl.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter st = new StreamWriter(S))
foreach (string a in ss) // In here i want set which lisbox I want to save
st.WriteLine(a.ToString());
}
}
What would be a good approach to the problem?
If you add a combobox that holds two items, Listbox1 and Listbox2 the following code will save the items from the listbox selected in the Combobox.
As you can see I add an items local variable that is of type ObjectCollection that is then assigned to using a switch statement.
private void button4_Click(object sender, EventArgs e)
{
ObjectCollection items = null;
switch (combobox1.Text) {
case "ListBox1":
items = listBox1.Items;
break;
case "ListBox2":
items = listBox2.Items;
break;
default:
throw new Exception("no selection");
break;
}
SaveFileDialog svl = new SaveFileDialog();
svl = saveFileDialog1;
svl.Filter = "txt files (*.txt)|*.txt";
if (svl.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter st = new StreamWriter(S))
foreach (string a in items) //the selected objectcollection
st.WriteLine(a.ToString());
}
If you don't have references to your listboxes you could dynamically add the listboxes that are on the form to the combobox in the load event of the form like so:
foreach(var ctl in this.Controls)
{
if (ctl is ListBox)
{
var lb = (ListBox) ctl;
this.comboBox1.Items.Add(lb.Name);
}
}
To find the correct listbox when you click save replace the switch command with this single line:
var items = ((ListBox) this.Controls[combobox1.Text]).Items;
You might want to check if combobox1.Text is emtpy or null but I leave that as an exercise for the reader.
I'd like to have a user select a folder with the FolderBrowserDialog and have the files loaded into the ListView.
My intention is to make a little playlist of sorts so I have to modify a couple of properties of the ListView control I'm assuming. What properties should I set on the control?
How can I achive this?
Surely you just need to do the following:
FolderBrowserDialog folderPicker = new FolderBrowserDialog();
if (folderPicker.ShowDialog() == DialogResult.OK)
{
ListView1.Items.Clear();
string[] files = Directory.GetFiles(folderPicker.SelectedPath);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
ListView1.Items.Add(item);
}
}
Then to get the file out again, do the following on a button press or another event:
if (ListView1.SelectedItems.Count > 0)
{
ListViewItem selected = ListView1.SelectedItems[0];
string selectedFilePath = selected.Tag.ToString();
PlayYourFile(selectedFilePath);
}
else
{
// Show a message
}
For best viewing, set your ListView to Details Mode:
ListView1.View = View.Details;
A basic function could look like this:
public void DisplayFolder ( string folderPath )
{
string[ ] files = System.IO.Directory.GetFiles( folderPath );
for ( int x = 0 ; x < files.Length ; x++ )
{
lvFiles.Items.Add( files[x]);
}
}
List item
private void buttonOK_Click_1(object sender, EventArgs e)
{
DirectoryInfo FileNm = new DirectoryInfo(Application.StartupPath);
var filename = FileNm.GetFiles("CONFIG_*.csv");
//Filename CONFIG_123.csv,CONFIG_abc.csv,etc
foreach(FileInfo f in filename)
listViewFileNames.Items.Add(f.ToString());
}