The DataGrid control in the Silverlight is one of the very important and useful controls. It is highly customizable with support of sorting, editing, grouping and paging. Here, this tutorial will talk about how to add data dynamically into the DataGrid. Specifically, it lets the user to input the Staff data during run time, as many as he/she likes.
Here the example of output in Silverlight that I have made:
Add a DataGrid by Drag and Drop, then add 3 columns
Note that each column has a binding path to the variable it displays.
<sdk:DataGrid AutoGenerateColumns="False" Height="206" HorizontalAlignment="Left" Margin="12,65,0,0" Name="myDataGrid" VerticalAlignment="Top" Width="352" >
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Header="Name" Binding="{Binding Path=staffName, Mode=OneWay}" Width="120"></sdk:DataGridTextColumn>
<sdk:DataGridTextColumn Header="ID" Binding="{Binding Path=staffID, Mode=OneWay}" Width="100"></sdk:DataGridTextColumn>
<sdk:DataGridTextColumn Header="Age" Binding="{Binding Path=staffAge, Mode=OneWay}" Width="100"></sdk:DataGridTextColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
Create a class for the Data Object. Eg: Staff.cs
Define the variables which used in the data binding in the class
public string staffName { get; set; }
public string staffID { get; set; }
public string staffAge { get; set; }
public Staff(string _name, string _id, string _age)
{
staffName = _name;
staffID = _id;
staffAge = _age;
}
Add Button
This is the button that fires the event assigning the values. Here, I use ObservableCollection<Staff> to store the data inside the DataGrid. (Define it as a global variable).
private void AddButton_Click(object sender, RoutedEventArgs e)
{
//Get the text from the textboxes
string _name = textBox1.Text;
string _id = textBox2.Text;
string _age = textBox3.Text;
//Add them inside the ObservableCollection variable: collectionInRow
collectionInRow.Add(new Staff(_name, _id, _age));
//This is the Most Vital line: assign the Source of the dataGrid to the ObservableCollection
myDataGrid.ItemsSource = collectionInRow;
}
Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.