Reputation: 137
I have one browse button and one text box. In the browse_button click event, I would like to browse the files and place the path name into textbox. For this I've written code like this by using openfile dialog.
private void brwsbtn_Click(object sender, EventArgs e)
{
if (openFD.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFD.FileName;
}
textBox1.Text="";
}
So that I am able to select files only. How can I select and place the folders path in textbox?.
In my application the user should able to select either file or folder through a single browse button. Please suggest me how to write code for this.
Note. Please let me know can we use to upload file without using Openfiledialog in windows form..
Upvotes: 3
Views: 34394
Reputation: 8025
Your code don't add file path to the text box because you have this line:
textBox1.Text = "";
Which auto clear the line:
textBox1.Text = openFD.FileName;
Remove it and you can add file path to textbox:
private void brwsbtn_Click(object sender, EventArgs e)
{
if (openFD.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFD.FileName;
}
}
If you want file name only (not include path), you can use:
private void brwsbtn_Click(object sender, EventArgs e)
{
if (openFD.ShowDialog() == DialogResult.OK)
{
textBox1.Text = Path.GetFileName(openFD.FileName);
}
}
Upvotes: 3
Reputation: 1884
Add a FolderBrowserDialog to your form. Then something like this will work:
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath
}
You can also use your existing fileDialog to do
Path.GetDirectoryName(openFD.FileName);
Upvotes: 1