views:

449

answers:

1

Hi,

I am implementing a file upload tool using Silverlight. In this I can browse for files and when I select a file then it is bound to a datagrid. In the datagrid I have a template column with a button to delete the particular item from the datagrid and ItemSource of the datagrid which is a List<>.

I have a class UploadedFiles as below.

public class UploadedFiles
{
    public FileInfo FileInf{get;set;}
    public int UniqueID{get;set;}
    public string FileName{get;set;}
    public string FileExtension{get;set;}
    public long FileSize{get;set;}
}

I am using a datagrid with a templatecolumn like below with ItemSource set as List<UploadedFiles>

<data:DataGridTemplateColumn Width="100">
  <data:DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <Button Click="btn_Click" Content="Del" Width="45"/>
    </DataTemplate>
   </data:DataGridTemplateColumn.CellTemplate>
  </data:DataGridTemplateColumn>

and the button click event handler is

private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
    /* I need to access the particular list item based on the datagrid
       row in which the clicked button resides.*/
}

I need to access the particular list item based on the datagrid row in which the clicked button resides and remove the item from the List<UploadedFiles> and rebind the datagrid.

Thanks

+1  A: 

Two things to look at here:

Firstly, to get the individual UploadedFiles object, cast the sender to a Button (or FrameworkElement) and access the DataContext property. The DataContext will be the UploadedFiles row (you will need to cast again from object).

Secondly, rather than removing the item from the list and rebinding, have you considered using an ObservableCollection instead? If you use that, removing the row will automatically remove it from the DataGrid without needing you to rebind.

private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
    var uploadedFiles = (UploadedFiles)((FrameworkElement)sender).DataContext;

    //access collection and remove element
}
Gareth Saul
+1 for the answer @Gareth.
rahul