Pass file path from file in listbox to dataconext C# - c#

I am populating a listbox with a file. This can be done by two methods, the open file dialog command initiated by a button press and a drag/drop action into the listbox. I want to pass on the file path (for the file in the listbox) to other areas of my code, for example the DataContext that reads the file in the listbox. Basically I want the file path to automatically update when the listbox is populated. I am new to C# so sorry if I haven't explained myself properly or provided enough information. The code for populating my listbox (named FilePathBox) and the 'Run' button is as follows:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.Multiselect = true;
openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog())
{
FilePathBox.Items.Clear();
foreach (string filename in openFileDialog.FileNames)
{
ListBoxItem selectedFile = new ListBoxItem();
selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
selectedFile.ToolTip = filename;
FilePathBox.Items.Add(selectedFile);
}
}
}
private void FilesDropped(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
FilePathBox.Items.Clear();
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
FilePathBox.Items.Add(fileItem);
}
}
}
private void RunButton_Click(object sender, RoutedEventArgs e)
{
DataContext = OldNewService.ReadFile(#"C:\Users\Documents\Lookup Table.csv");
}

I added a comment, but I think what you need a way to get the selected file path when the RunButton is clicked, so just add this to your RunButton_Click method,
private void RunButton_Click(object sender, RoutedEventArgs e)
{
string selection = (string)FilePathBox.SelectedItem;
DataContext = OldNewService.ReadFile(selection);
}

Related

C# - How to load text from text file in a listbox into a richTextBox?

Now solved. Thanks for your answers!
This is my code right now:
//Listbox scripts is the name of my folder
private void Form1_Load(object sender, EventArgs e)
{
foreach (var file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + #"Listbox scripts"))
{
string file2 = file.Split('\\').Last();
listBox1.Items.Add(file2);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("SetText", new object[]
{
File.ReadAllText(string.Format("./Listbox scripts/{0}", listBox1.SelectedItem.ToString()))
});
}
I'm new to coding in C# and I have a textbox that has the names of text files in a directory and when I click on the text file in the listbox it's supposed to load the text from it into my textbox (named 'ScriptBox')
Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
string User = System.Environment.MachineName;
textBox1.Text = "{CONSOLE} Welcome to Linst, " + User + "!";
directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + #"Scripts");
files = directory.GetFiles("*.txt");
foreach (FileInfo file in files)
{
listBox1.Items.Add(file.Name);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedFile = files[listBox1.SelectedIndex];
ScriptBox.Text = File.ReadAllText(selectedFile.FullName); //these parts are the parts that dont work
}
Thanks in advance!
Add the below into your Form1.cs. What this is going to do is when a user clicks a listbox item, its going to call (raise an event) the "listBox1_MouseClick" method and set the text of the textbox to the text of the listbox item. I just quickly created an app and implemented the below and it works.
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Text = listBox1.Text;
}
And add the below to the Form1.Designer.cs where the rest of your list box properties are. The below is subscribing to an event, the listBox1_MouseClick method in Form1.cs, so when a user clicks on a listbox item, the listBox1_MouseClick method is going to run.
this.listBox1.MouseClick += new MouseEventHandler(this.listBox1_MouseClick);
I hope the above makes sense.
Your code is nice, and perfect but it just need a little validation check in list index selection
Try thing in your listbox_selectedIndexChanged
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex!=-1)
{
FileInfo selectedFile = files[listBox1.SelectedIndex];
ScriptBox.Text = File.ReadAllText(selectedFile.FullName);
}
}
I actually don't see a problem with your code, could it be a typo somewhere?
I did this and it worked for me:
private void Form1_Load(object sender, EventArgs e)
{
foreach (var file in System.IO.Directory.GetFiles(#"c:\"))
{
listBox1.Items.Add(file);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
textBox1.Text = System.IO.File.ReadAllText(listBox1.SelectedItem.ToString());
}
}

How do i read already opened file in a another button click event directly .(i.e without open file dialogue in button click)

void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
var geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
}
How to read files in button1 click directly?
what you want is that your geometry object be accessible in additional scopes besides OpenPolyFile(). So you can simply make the geometry declaration accessible to both methods, declaring it, say, in the form code behind
// class scoped variables
[ThePolyFileType] (pick the right one here :) geometry = null;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
if (geometry != null)
{
//do your stuff
}
}
How do i read already opened file in a another button click event
directly .(i.e without open file dialogue in button click)
I'm not quite sure why you want to read it twice, but if that requirement says, make selected filename available globally and use it.
private string filename;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
filename = ofd.FileName
}
}
Now you have opened filename available in button_clcik you can use this file and read again.
private void button1_Click(object sender, EventArgs e)
{
// now you can read the file.
//File.ReadAllText(filename); //OR
TriangleNet.IO.FileReader.ReadPolyFile(file);
}

How to view selected item in listbox in image viewer asp.net

I have this code that populates my listbox that contains what I type in the textbox. My problem is how can I view the selected item in my listbox in a image viewer since all my files are images? Am I missing something?
Here's my code:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DocumentImage.ImageUrl = Directory.GetDirectories("~/images") + ListBox1.SelectedItem.ToString();
}
This should work I think:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
string subPath = item.Substring(Server.MapPath("~/images").Length).Replace("\\","/");
ListBox1.Items.Add(new ListItem(fileName, subPath));
}
}
}
In this part, you need to not only have the file name, but also the path where the file was found. In my sample, the sub path where the file was found is first set into subPath and that is then stored as the value for the list item.
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DocumentImage.ImageUrl = "~/images" + ListBox1.SelectedItem.Value;
}
Here we use the sub path to set the correct url to the image.
Note that you need to have the AutoPostBack set to true on the DocumentImage in your asxp page in order for the image to change when you change the selection in the list box.

Prevent duplication in ListView?

I have made a simple application in Visual studio using C# that basically browses a folder, and the path of folder comes in text box - 'HideFolderAddress'. When the button 'AddToListBtn' is clicked it checks if there is a presence of the same item and if not it adds the item to list.
But this Prevent duplication in list view does not seems working! Can some one help me?
private void BrowsHide_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
HideFolderAddress.Text = fd.SelectedPath;
HideFolderAddress.Tag = Path.GetFileName(fd.SelectedPath);
}
}
private void AddToListBtn_Click(object sender, EventArgs e)
{
ListViewItem itemList = new ListViewItem(HideFolderAddress.Tag.ToString());
if (!FolderList.Items.ContainsKey(HideFolderAddress.Tag.ToString()))
{
itemList.SubItems.Add(HideFolderAddress.Text);
FolderList.Items.Add(itemList);
}
}
use it this way , because there will be no key if it is not created via Add method of ListViewItemCollection.
private void AddToListBtn_Click(object sender, EventArgs e)
{
string itemTag = HideFolderAddress.Tag.ToString();
if (!FolderList.Items.ContainsKey(itemTag ))
{
ListViewItem itemList = FolderList.Items.Add(itemTag , itemTag , -1);
itemList.SubItems.Add(HideFolderAddress.Text);
}
}

How do I show the filename in listbox but keep the relative path using openfiledialog?

I am making a program in which the user needs to load in multiple files. However, in the ListBox I need to show only file names of the files they loaded but still be able to use the files loaded. So I want to hide the full path. This is how I load a file into the ListBox now, but it shows the whole path:
private void browseBttn_Click(object sender, EventArgs e)
{
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)
{
dllList.Items.AddRange(OpenFileDialog1.FileNames);
}
}
// Set a global variable to hold all the selected files result
List<String> fullFileName;
// Browse button handler
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Seclect 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)
{
dllList.Items.Add(fileName.Substring(fileName.LastIndexOf(#"\")+1));
}
}
}
// handle the selected change if you wish and get the full path from the selectedIndex.
private void dllList_SelectedIndexChanged(object sender, EventArgs e)
{
// check to make sure there is a selected item
if (dllList.SelectedIndex > -1)
{
string fullPath = fullFileName[dllList.SelectedIndex];
// remove the item from the list
fullFileName.RemoveAt(dllList.SelectedIndex);
dllList.Items.Remove(dllList.SelectedItem);
}
}
You can extract the fileName of the absolute path using the static Class Path in the System.IO namespace
//returns only the filename of an absolute path.
Path.GetFileName("FilePath");

Categories