Element Element - 3 months ago 33
C# Question

c# Access a DataTable from all classes in project (using properties)

I have an application i've been working on to help teach myself c#.net. I've come to the point where i'm starting to use classes to organise my project and save me having to copy / paste code everywhere.

On my main form i have a Datalist view which i intend to use as a console for ouputting log entries.

I've made a class called "logger" which has the following:

public DataTable DTLog = new DataTable();

public void BuldDTLog()
{
DTLog.Columns.Add("Time");
DTLog.Columns.Add("Type");
DTLog.Columns.Add("Level");
DTLog.Columns.Add("Text");
}

public void AppendtoLog(String Level, String Type, String Text)
{

DTLog.Rows.Add(DateTime.Now, Level, Type, Text);

}


I call BuildDtLog() from my frmMain which builds the DataTable
I then call AppendtoLog("1", "Info", "This is a test log entry"); from a button on frmMain and the entry is added to the datatable.

My problem is when i come to add an entry to the datatable from another class. I get "Object reference not set to an instance of an object" in AppendtoLog. - As if the datatable doesn't exist anymore?

I've looked at properties, i've run through a couple of examples and kind of understand how they work and that they could help me in this situation but i'm really struggling to understand how to implement it into my situation. Could someone help?

Thanks

Answer

make your log class and its functions static and call that function from any class

public static logger
{
 public DataTable DTLog = new DataTable();

public static void BuldDTLog()
        {
            DTLog.Columns.Add("Time");
            DTLog.Columns.Add("Type");
            DTLog.Columns.Add("Level");
            DTLog.Columns.Add("Text");
        }

        public static void AppendtoLog(String Level, String Type, String Text)
        {

            DTLog.Rows.Add(DateTime.Now, Level, Type, Text);

        }
}

public class otherClass
{
logger.BuldDTLog();
logger.AppendtoLog(param1,param2,param3);
}