开发者

Binding forename and surname fields to a label?

I have a table associating an ID with a client's forename and surname (two separate fields). I have a TextBox on my form for a user to enter a client ID and I'd like a live update of the name displayed on a label, e.g.:

TextBox:  1  -->  Label: "Sam Pell"    (user types 1)
TextBox: 12  -->  Label: "Andy Other"  (user types 2)

I have two questions, really - I'm new to databinding in .NET:

  • How 开发者_如何学运维can I make the contents of the TextBox update the displayed name on the Label?
  • How can I display two separate fields (concatenated) within a single Label control?

I am currently using the Visual Studio data binding components; namely a BindingSource, TableAdapter and DataSet.


The type you are binding could have a readonly property that has a concatenated value.

public class Person
{
    string Forename { get; set; }
    string Surname { get; set; }
    string FullName 
    {
        get { return String.Format("{0} {1}", Forename, Surname); }
    }
}

Then bind FullName property to your label control.

In case you are using DataSet, then Add a custom column to your DataTable, with expression "forename + ' ' + surname". More info here.

To update label you have to handle TextChanged event of your text box:

textBox1.TextChanged += () => label1.Text = (string) dt.Rows.Find(textBox1.Text)["columnName"];

where column name is the name of your new column.


How are you getting the values from the database? You could perhaps modify your query to concatenate the values like this;

SELECT firstName + " " + surname FROM user

So you've just got one value to contend with when databinding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜