Append text to Top of Textbox

2020-05-08 08:44发布

问题:

While populating a Textbox using a List. The Display method is as follows.

 private void Display()
    {
        StringBuilder sb = new StringBuilder();
        foreach (Player dude in _FootballRoster)
        {
            if (btnUSA.Checked == true)
            {
                sb.AppendLine("\r\nName: " + dude.getName() + " \r\n Team: " + dude.getTeam() + "\r\n Birthday: " + dude.getBirthday() + "\r\n Height(in):" + dude.getHeight() + "\r\n Weight(lbs): " + dude.getWeight() + "\r\n Salary(USD): " + dude.getSalary());
            }
            if (btnUSA.Checked == false)
            {
                sb.AppendLine("\r\nName: " + dude.getName() + " \r\n Team: " + dude.getTeam() + "\r\n Birthday: " + dude.getBirthday() + "\r\n Height(meters):" + (dude.getHeight()) / 39.3701 + "\r\n Weight(kg): " + (dude.getWeight()) / 2.20462 + "\r\n Salary(CD): " + (dude.getSalary()) / 1.31);
            }
        }
        txtRosterLog.Text = sb.ToString();
    }

While trying to implement a Sort method when you click btnName, I want "SORT BY: NAME" to appear at the top of the textbox but my current code puts it at the bottom of all the players.

Current Name Sort Code:

private void btnName_Click(object sender, EventArgs e)
    {

        _FootballRoster = _FootballRoster.OrderBy(dude => dude.Name).ToList();
        Display();
        txtRosterLog.AppendText("SORT BY: NAME ");

    }

Any ideas? I've tried using txtRosterLog.Text.Insert(0, "SORT BY NAME)" but that didn't work either.

回答1:

txtRosterLog.Text = "SORT BY: NAME \r\n" + txtRosterLog.Text;

txtRosterLog.Text.Insert(0, "SORT BY NAME)" would also work if you assign it back:

txtRosterLog.Text = txtRosterLog.Text.Insert(0, "SORT BY NAME");


回答2:

I would go with String.Format as it is quite flexible and easly readable if you would like to make your string more fancy in future.

String s = String.Format("SORT BY: NAME \r\n {0}", txtRosterLog.Text);