Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF, how to implement a file upload control (textbox and a button to browse file)?

I have a WPF,MVVM application.

I need the functionality same as "File Upload" control in asp.net.

Can somebody tell me how to implement that ?

 <StackPanel Orientation="Horizontal">
                <TextBox Width="150"></TextBox>
                <Button Width="50" Content="Browse"></Button>
</StackPanel>

I have this xaml...but how to have that "browse window" when you click button ?

like image 645
Relativity Avatar asked Feb 02 '11 16:02

Relativity


People also ask

How to Upload a file in WPF?

You can simply double click on the Button to add its click handler. On the button click event handler, we will write code to launch the OpenFileDialog and select a text file. The Button click event handler code is listed in Listing 2. Nullable<bool> result = openFileDlg.

How do I add a file upload control in Windows Forms?

Select Files, and then choose the Apps folder. Select the Microsoft Forms folder. Select the file folder matching the name of your form. Select the folder of the question that has uploaded files.


2 Answers

You can use OpenFileDialog class to get a file choose dialog

OpenFileDialog fileDialog= new OpenFileDialog(); 
fileDialog.DefaultExt = ".txt"; // Required file extension 
fileDialog.Filter = "Text documents (.txt)|*.txt"; // Optional file extensions

fileDialog.ShowDialog(); 

To read the content : You will get the filename from the OpenFileDialog and use that to do what IO operation on it.

if (fileDialog.ShowDialog() == DialogResult.OK)
{
     System.IO.StreamReader sr = new System.IO.StreamReader(fileDialog.FileName);
     MessageBox.Show(sr.ReadToEnd());
     sr.Close();
}
like image 103
Jobi Joy Avatar answered Sep 28 '22 12:09

Jobi Joy


<StackPanel Orientation="Horizontal">
     <TextBox Width="150"></TextBox>
     <Button Width="50" Content="Browse" Command="{Binding Path=CommandInViewModel}"></Button>
</StackPanel>

Declare a command in your view model and bind it in the view as I have done inside button. Now you will get control in the code once user will click the button. In that code create a window and launch it. Once user will close the window, read the contents and do whatever you want.

like image 31
Haris Hasan Avatar answered Sep 28 '22 13:09

Haris Hasan