BoKKeR BoKKeR - 25 days ago 16
C# Question

c# wpf, trying to load data into a specific forms datagrid from a static method

I am trying to load from a static method some data into my mainwindow-s datagrid (adding columns), I am trying to achieve this without creating a new instance of the window. I have hacked together a way to get around the static limitations but it fails with a error

public partial class MainWindow : MetroWindow
{
static MainWindow mainWindow;
public MainWindow()
{

InitializeComponent();
ArgumentLoader();
SqliteDatabase.check_for_database();
SqliteDatabase.load_database();
ColumnLoader("alias");

}

public static void ColumnLoader(string alias)
{
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = "X";
textColumn.Binding = new Binding("X");
mainWindow.dataGrid.Columns.Add(textColumn);
}


exception

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

Additional information: Exception has been thrown by the target of an invocation.

if I rename

mainWindow.dataGrid.Columns.Add(textColumn);


to

dataGrid.Columns.Add(textColumn);


and make the method non-static it works. Am I missing something or is there a better way to do this ?

Answer

You need to set mainWindow to the object instance. You can do so in the constructor:

public MainWindow()
{
    mainWindow = this;

    InitializeComponent();
    ArgumentLoader();
    SqliteDatabase.check_for_database();
    SqliteDatabase.load_database();
    ColumnLoader("alias");
}
Comments