How to Edit the Silverlight Datagrid
Learning how to edit a DataGrid control in your Silverlight project can make your application more dynamic by editing cell values quickly. You can develop Silverlight projects using C# and XAML. XAML is a markup language that can simplify the creation of user interface elements such as DataGrids and buttons. One way you can populate a DataGrid is by using a “List” class. A “List” can be thought of like an array of objects that can be accessed by index.
Instructions
-
-
1
Launch Microsoft Visual Studio, click the “New Project” link to launch the New Project dialog window. Expand “Other Language” below Installed Templates and click “Silverlight.” Double-click “Silverlight Application” to create a new project. Leave the default settings in the New Silverlight Application dialog window and click “OK.”
-
2
Double-click “DataGrid” to add a new data grid control to your project. Add a button using the same technique. Double-click “Button” to launch the code module and create a click event for the button. Add the following code to edit the grid with new values when the button is clicked:
List<Authors> newAuthors = new List<Authors>()
{
new Authors()
{
Name = "Jaime",
Username = "Shadow",
Language = "VB.NET"
},
new Authors()
{
Name = "Oscar",
Username = "admin",
Language = "Python"
},
};
dataGrid1.ItemsSource = newAuthors; -
-
3
Copy and paste the following code below “namespace SilverlightApplication {” to create a new class:
public class Authors
{
public string Name { get; set; }
public string Username { get; set; }
public string Language { get; set; }
} -
4
Populate the DataGrid control with values when you launch your program by adding the following code:
DataGridTextColumn textColumn1 = new DataGridTextColumn();
textColumn1.Header = "Name";
textColumn1.Binding = new Binding("Name");
dataGrid1.Columns.Add(textColumn1);DataGridTextColumn textColumn2 = new DataGridTextColumn();
textColumn2.Header = "Username";
textColumn2.Binding = new Binding("Username");
dataGrid1.Columns.Add(textColumn2);DataGridTextColumn textColumn3 = new DataGridTextColumn();
textColumn3.Header = "Language";
textColumn3.Binding = new Binding("Language");
dataGrid1.Columns.Add(textColumn3);List<Authors> author = new List<Authors>()
{
new Authors()
{
Name = "Brandon",
Username = "The Reddest",
Language = "C#"
},
new Authors()
{
Name = "Charlie",
Username = "The Fattest",
Language = "ActionScript"
},
};dataGrid1.ItemsSource = author;
-
5
Press the “F5” key to run your project and view the default values. Edit the DataGrid control by clicking the “Button” control.
-
1
References
- Photo Credit Ryan McVay/Photodisc/Getty Images