views:

61

answers:

2

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.

A: 

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.

C.McAtackney
I have a DataSet with TableAdapters and a BindingSource - I haven't written any SQL, so couldn't concatenate them like that?
Rezzie
+1  A: 

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.

Al Bundy
I need the label to display the name of a client based on the ID entered into the textbox, just to just replicate the text.
Rezzie
Thank you. Very helpful.
Rezzie