DataGrid Column Resize After Row Delete In Silverlight 3
Introduction
In this article, we will see how we can resize the DataGrid Column after Row Delete Operation from the DataGrid.
Problem
For DataGrid Column we have 4 modes to select the width. Such as Pixels, Size to Header, Size to Cell and Auto.
When you insert a long text for your DataGrid Column the width of the Column changes accordingly, but when you remove the particular row the Column width remains the same.
It should resize back to the required column width.
Creating Silverlight Project
Fire up Visual Studio 2008 and create a new Silverlight 3 Project. Name it as DataGridColumnResize.
Add some controls like TextBox and Buttons along with one DataGrid to your application.
I have opened the solution in Blend and designed as follows:
Now what we see from the above design is that, we would add a row to the DataGrid and can remove the row.
I have customized the DataGrid Control so that MouseScroll can be achieved. And I have added two columns to display Data.
Here is the XAML to follow up quickly.
<locals:DataGridEx x:Name=”dgMyGrid” CanUserResizeColumns=”False” IsReadOnly=”True” AutoGenerateColumns=”False”
Content=”Remove Selected Row” Margin=”8,8,0,0″ Grid.Column=”1″ Grid.Row=”3″ Height=”24″ VerticalAlignment=”Top” HorizontalAlignment=”Left” Width=”150″/> |
Now we will write some sample data and bind to the DataGrid.
public {
} List<People> myList = new
{ InitializeComponent(); myList = new {
}; dgMyGrid.ItemsSource = myList; } |
Now we will write a method that would resize the DataGrid Column.
private {
{
columns.Add(column); }
{ column.Width = new } grid.UpdateLayout();
{ column.Width = DataGridLength.SizeToCells; } grid.UpdateLayout(); } |
Now we will write the Add Button Click Event Handler.
private { myList.Add(new dgMyGrid.ItemsSource = myList; ResetColumnWidth(dgMyGrid); } |
Now we will write the Remove Selected Row Button Click Handler.
private {
{ myList.Remove(this.dgMyGrid.SelectedItem as dgMyGrid.ItemsSource = myList; } ResetColumnWidth(dgMyGrid); } |
That’s it. Run your application and try adding a long text to the DataGrid.
As you see from the above image, Column width has changed when this new row is added to DataGrid.
Now we would remove the Long Text row.
As you see, the Column width is resized.
Hope this article helps you. J
Dipti,
I am trying to prevent an autogenerated bound column cell from stretching downwards when the column is collapsed. Can you suggest whether this reset function will work for that scenarion and which datagrid event i would call it from??