Saturday, January 10, 2009

Silverlight Datagrid find row number

Silverlight 2.0 datagrid has rich UI features giving very impressive look and feel. I am trying to add to a list of difficult to find tricks which might be helpful to others. I could not obviously find these while I did the google search, so I am writing this now.

Adding a button column to Silverlight Grid:


<data:datagrid name="gridCustomers" autogeneratecolumns="False" headersvisibility="All" gridlinesvisibility="All" isreadonly="True" rowbackground="Cornsilk" alternatingrowbackground="LemonChiffon"
ColumnWidth="85" RowHeight="30" CanUserResizeColumns="False" Canvas.Top="603" Canvas.Left="16" Width="1072" Height="120" SelectionMode="Single" >
<data:datagrid.columns>
<data:datagridtextcolumn header="Id" binding="{Binding id}">
<data:datagridtextcolumn header="Location Name" binding="{Binding Name}">

<data:datagridtemplatecolumn header="Edit">
<data:datagridtemplatecolumn.celltemplate>
<datatemplate>
<button content="Edit" margin="4" tag="{Binding customlocationid}" click="datagridEditRow_Click"></button>
</datatemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
<data:datagridtemplatecolumn header="">
<data:datagridtemplatecolumn.celltemplate>
<datatemplate>
<button content="Delete" margin="4" tag="{Binding customlocationid}" click="datagridDeleteRow_Click"></button>
</datatemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>


The above code gives the WPF markup for the grid. See the bold font for the Templated Column definitions for the "Edit" and "Delete" buttons.

Finding the row numbers:
  Now our button click event handlers datagridEditRow_Click and datagridDeleteRow_Click will need to know the row numbers when they are clicked. 

  We cannot use the gridCustomers.SelectedItem for this. The reason is, a click on the button won't automatically select the row. So we have to use the following code.
        private void datagridEditRow_Click(object sender, RoutedEventArgs e)
        {
            Button btnSender = (Button)e.OriginalSource;
            int dgridrow = DataGridRow.GetRowContainingElement(btnSender).GetIndex();
            gridLocations.SelectedIndex = dgridrow;
      }

 The above code will automatically get us the row number and we can use it to find the data in the row or may be select that row by setting the selectedindex property.

No comments: