简体   繁体   中英

Passing a string from one page to another in Xamarin.Forms

All i want is to pass my Entry Text from one page to another. Not in Xaml but in .cs file.

First page code

<Label Text="Username" TextColor="Gold" FontSize="Small"/>
<Entry Placeholder="Username" TextColor="White" x:Name="Username"/>

Username.Text will be used for the Text. I want this text on my second page.

Second page where i want this Username.Text

sqlcmd.CommandText = queryString;
sqlcmd.Parameters.AddWithValue("@n", {I want Username.Text here });

Thank You.

There are many ways to do this depending on how you have structured your app.

If the page is already open you can use MessagingCenter to send from one ViewModel or Page To the other

Sender

MessagingCenter.Send<MainPage> (this, "Hi");

Receiver

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});

If you are creating the Page , you can just pass in the text through the Page Constructor ,

New Page Constructor

public MyPage(string someText)
{
}

Sender

await Navigation.PushAsync(new NavigationPage(new MyPage(<YourTextHere>)));

or via a Property

await Navigation.PushAsync(new NavigationPage(new MyPage() { SomneProperty = "blach" ));

Additional Resources

Xamarin.Forms.INavigation.PushAsync Method

How the MessagingCenter Works

So i had a Tabbed Page with 5 pages in it. What i did is this.

Passed my Username.Text like this

 Navigation.PushModalAsync(new Overview(Username.Text));

Then retrieved it like this in the Overview Page.

 public string str = null;
    public Overview (string g)
    {
        str = g;

        this.Children.Add(new Home()
        {
            Title = "Home",
            Icon = "",
        });
        this.Children.Add(new EarnPoints(str)
        {
            Title = "Earn More",
            Icon = "",
        });

And then finally in my EarnPoints page i did this.

 public string sts = null;
    public EarnPoints (string g)
    {
        InitializeComponent ();

        sts = g;

        GetAccountCountFromMySQL();  
    }

    public void GetAccountCountFromMySQL()
    {
        try
        {
            MySqlConnection sqlconn;
            string connsqlstring = "Server=lightningstorerewards.com;database=sukree_dzgpt;User Id=sukree_gptuser;Password=kgausi9nMNzX;charset=utf8";
            sqlconn = new MySqlConnection(connsqlstring);
            sqlconn.Open();
            string queryString = "SELECT points FROM users WHERE username = @n";
            MySqlCommand sqlcmd = new MySqlCommand(queryString, sqlconn);
            sqlcmd.CommandText = queryString;
            sqlcmd.Parameters.AddWithValue("@n", sts);

Thanks for all your help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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