Reputation: 289
C# n00b here. I can't figure out why I get the error on TextBox.text
saying:
On googling the error, it seems like it's to do with my TextBox being static..? I can you please explain what this all means? How do I make it non-static? I have a good background in Java, Obj-C, Python and Swift if you can draw any similarities from there.
Code:
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "Text Files (*.txt)|*.text";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result.HasValue && result.Value)
{
// Open document
string filename = dlg.FileName;
TextBox.Text = filename;
}
}
}
}
Upvotes: 1
Views: 1693
Reputation: 36473
Text
is an instance property. So you need to invoke it using an instance of the TextBox
class.
When you do:
TextBox.Text = filename; // "TextBox" is a class, not an instance.
You are trying to invoke Text
as if it was a static property, but it isn't.
So I don't know if you do have an instance of a TextBox
somewhere in your window. If you added one to your WPF app, by default in VS2015 it will be called textBox
(which can easily be confused with TextBox
). Whatever it's called, you'll want to use that to set the Text
property. Like this:
// consider prefixing with "this" to make sure
// you are using an instance name and not a class name by mistake.
this.textBox.Text = filename;
Upvotes: 1
Reputation: 2688
TextBox
is a control name and I don't think you can use TextBox.Tex = filename;
You need to give a name to your TextBox
control using the Name
property in XAML and then assign value to the Text
property in your code behind file.
Something like, name your text box as txtFileName
and then try assigning value like txtFileName.Text = filename;
Also, giving a name like Button
to an event will definitely cause exception. You should better use some name like OnButtonClick
to handle the Button Click event, rather than private void Button()
.
Upvotes: 1
Reputation: 6981
If you have a TextBox in your xaml, like this:
<TextBox Name="textBox1" Width="100" Height="50" />
you can reference it from the code behind (in your example the MainWindow
class) by the name like this:
textBox1.Text = "Hello World";
The class TextBox is not a static class. For more info on static class see this post:
Upvotes: 2