1

I'm using a two column (ID,NAME) DataGrid and want update the row with new values.

I'm not sure how I can use the binding part in my C# code.

 <DataGrid Name="dataGridUser" ItemsSource="{Binding}" VerticalAlignment="Top" Width="auto" Grid.RowSpan="2"/>

How can I update the datagrid with net values like :

ID , Name 123, Peter 345, Simon ....

1
  • 5
    ItemsSource should have a binding like {Binding MyItems} where MyItems would be an ObservableCollection and you would have it as a public property in whatever data source you have active. Commented Jul 30, 2013 at 20:44

1 Answer 1

1

So to give you an Example, first create a Model

public class User
{
    public int ID { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

then in your Code-Behind File create an ObservableCollection of that Model

private ObservableCollection<User> _myUsers;

    public ObservableCollection<User> MyUsers
    {
        get
        {
            if (_myUsers == null)
            {
                _myUsers = new ObservableCollection<User>();
            }
            return _myUsers;
        }
    }

and now you can bind your DataGrid to this Property

<DataGrid Grid.Row="1" Name="dataGridUser" ItemsSource="{Binding MyUsers}" AutoGenerateColumns="True"/>

and don´t forget to set the DataContext

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"></Window>

if you add a new User to the ObservableCollection MyUsers it will immediately be displayed in your DataGrid, but if you change the FirstName of a existing User it will not display the changes. To do this you must implement INotityPropertyChanged in your Model.

But if you plan to develop a more complex Application I would recommend to take a look at the MVVM-Pattern.

Personally I like the MVVM Light Toolkit this Video should give you a good Idea what MVVM is all about.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.