views:

72

answers:

3

I have a C# WPF app that every time the user opens a new file, the contents are displayed in a datagrid.

public partial class MainWindow : Window
{
     public TabControl tc = new TabControl();

     public MainWindow()
     {
         InitializeComponents();
     }

     private FromFile_click(object sender, RoutedEventArgs e)
     {
         //gets information from file and then...

         if (numberOfFiles == 0)
         {
             masterGrid.Children.Add(tc);
         }
         TabItem ti = new TabItem();
         tc.Items.Add(ti);

         DataGrid dg = new DataGrid();
         ti.Content = dg;

         dg.Name = "Grid"+ ++numberOfFiles;

         dg.ItemSource = data;
     }

     private otherMethod(object sender, RoutedEventArgs e)
     {

     }
}

My question is, how do I use the data in dg in the method "otherMethod"? Also, is it possible to change the parent of dg from the method "otherMethod"?

A: 

You have to pass it as a parameter to the other method otherMethod or make it a member variable.

Brian R. Bondy
+4  A: 

Assuming you're not calling otherMethod within FromFile_Click, you need to make it an instance variable - like your TabControl is, except hopefully not public. I'm assuming otherMethod is actually meant to handle an event of some kind, rather than being called directly.

Now this is assuming that you want one DataGrid per instance of MainWindow, associated with that window. If that's not the case, you'd need to provide more information.

Jon Skeet
'otherMethod' is meant to handle an event, some sort of button click I haven't defined yet. See, I can't make 'TabItem' or 'datagrid' an instance variable because I don't know how many files the user open.
anon
@anon: So if there could be two datagrids open, which one would you want `otherMethod` to refer to? If you can work *that* out, the rest may well become clear.
Jon Skeet
@Jon Skeet: What I'm trying to do is, change tabs into tile view when the user clicks a button. Example: Assume there are several tab open, each one has a datagrid with independent data. If the user clicks a button, then each of the datagrid will move to a individual tile (so a datagrid, being a child of a tab will change into a child of a tile). `tc` will be hidden, and `tv` (defined below) will become visible. The opposite can also happen.`private TileViewControl tv = new TileViewControl();` is added below where `tc` is defined.So i guess, `otherMethod` will refer to all the datagrids.
anon
Right - so if it's going to refer to *all* the datagrids, just have a `List<DataGrid>` variable instead.
Jon Skeet
A: 

set the DataGrid dg as a property instead of declaring inside the FromFile_click.

This way when you assign "dg" it will work from any other method (few restrictions apply)

VoodooChild