Hi Sir, Mam,
I would like to ask how can I access the textbox value like UserName in Login WPF into
another WPF form? I am trying to initialize the form LoginWindow objLogin = new LoginWindow ()
MessageBox.Show(objLogin.user_name_txt.Text); but it return null
Thank you.
Regards,
Rodel

Tahir AnsariRank #366 · 6.8K reputationPosted Sep 5, 2023, 2:11 AM EDT
Create a Property in the LoginWindow: In your LoginWindow class, create a public property that exposes the value of the user_name_txt TextBox. This allows you to access the value from another window.
public partial class LoginWindow : Window { public string UserName { get { return user_name_txt.Text; } } // ... }Initialize and Show the LoginWindow: In your other WPF window where you want to access the value, create an instance of LoginWindow, show it, and then access the UserName property to get the value
LoginWindow objLogin = new LoginWindow(); objLogin.ShowDialog(); // Use ShowDialog() for modal behavior string userName = objLogin.UserName; // Check if the user canceled the login or entered an empty username if (!string.IsNullOrEmpty(userName)) { MessageBox.Show(userName); }Make sure you call ShowDialog() instead of Show() if you want the login window to be modal, which means it will block interaction with other windows until it's closed.
Sam HobbsRank #107 · 20.5K reputationPosted Sep 6, 2023, 12:11 AM EDT
There are many ways to do it. You can use the LoginWindow class to store the data, as has been suggested. The professional way is to create a separate class and create an instance of that class outside of a form and then pass that instance to the other forms, including the LoginWindow class.