简体   繁体   English

初学者帮助C#在文本框中显示文件路径

[英]Beginners help C# showing a filepath in text box

I'm new to programming and am using C# and Visual Studio Express 2012. I am creating a windows form and have inserted a button which runs open file dialog when clicked. 我是编程和使用C#和Visual Studio Express 2012的新手。我正在创建一个Windows窗体并插入一个按钮,单击该按钮时会运行打开的文件对话框。 I have a text box on the form that I'd like to have show the file path of the file that the user selected. 我在表单上有一个文本框,我想显示用户选择的文件的文件路径。 I have found some code examples on this site but struggle to understand where they should be placed in the code structure as the examples are often standalone snippets. 我在这个网站上找到了一些代码示例,但很难理解它们应该放在代码结构中的哪个位置,因为示例通常是独立的代码片段。 I hope its not too dumb a question! 我希望它不是一个愚蠢的问题!

Thanks in advance 提前致谢

Lee 背风处

The answer in case it's of use to anyone was....... 如果对任何人都有用的答案是.......

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (FileDialog fileDialog = new OpenFileDialog())
        {
            if (DialogResult.OK == fileDialog.ShowDialog())
            {
                string filename = fileDialog.FileName;

                textBox1.Text = fileDialog.FileName;
            }
        }
    }
}

Your OpenFileDialog has property FileName that contains the path of the selected file, assign that to your TextBox.Text 您的OpenFileDialog具有属性FileName ,其中包含所选文件的路径,并将其分配给TextBox.Text

if (openFileDialog.ShowDialog() == DialogResult.OK)
{
    yourTextBox.Text = openFileDialog.FileName;            
}
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if(openFileDialog1.ShowDialog() == DialogResult.OK)
    textbox.text = openFileDialog1.FileName;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM