Home Getting a class property value from a textbox
Reply: 2

Getting a class property value from a textbox

Confused Published in 2017-12-07 21:56:11Z

I am wondering how to return the value of a class property with the input of a textbox? i.e. the input in the nameTextBox would go to the Name property of a Pet class, the breedTextBox would be the Breed property, etc.

Using C# windows form.

ispiro Reply to 2017-12-07 22:05:34Z
Pet pet = new Pet();
pet.Name = nameTextBox.Text;


If your question is how to get this code executed then either have an "update" Button, and in its Click event handler run this code, or subscribe to the Textbox's TextChanged event and do it there. (You can also use binding, a bit more complicated. See here.)

Tommaso Belluzzo
Tommaso Belluzzo Reply to 2017-12-07 22:09:46Z

This logic can be accomplished by handling the TextChanged event of your TextBox instances. Given the current Pet instance m_Pet (allocated within your class as a member, for example):

private Pet m_Pet = new Pet();

and the events subscription in the InitializeComponent method of the form:

m_TextBoxName = new TextBox();
m_TextBoxName.TextChanged += TextBoxName_TextChanged;

here is how you can accomplish this:

private void TextBoxName_TextChanged(Object sender, EventArgs e)
    m_Pet.Name = m_TextBoxName.Text;

And the same can be performed for as many properties as you want:

private void TextBoxBreed_TextChanged(Object sender, EventArgs e)
    m_Pet.Breed = m_TextBoxBreed.Text;

private void TextBoxType_TextChanged(Object sender, EventArgs e)
    m_Pet.Type = m_TextBoxType.Text;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304308 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO