Click here to Skip to main content
15,036,891 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi everyone, i have visual studio 2012 winform
i would like to make datatable accessible accessible anywhere in my app: accessible in every winform i will create i my app.

so far i have populated my datagridview from my database table and all these data fetched are stored in a datatable.
And now i want to make this datatable accessible in anywhere.

What I have tried:

conn = new MySqlConnection(strcon);

da = new MySqlDataAdapter();
string qry2 = "SELECT R_Nber_Id,Society_Name , Service_Category ,Service_Type ,Time_Created,Ticket_Created,Time_Resolved,Ticket_Resolved FROM medicine_jhatpat.childs_report;"
da.SelectCommand = new MySqlCommand(qry2, conn);
cb = new MySqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
Posted
Updated 15-May-16 18:50pm

C#
OK read following example: Say for example you have 2 forms Form1 and Form2. Also you have another class which contains property for static datatable and method to load data in that datatable.

The class will be like following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace TestApp
{
    public class UserClass
    {
        //Define your static data table
        public static DataTable UserDataTable { get; set; } = new DataTable();

        //Get user data from database and load in datatable///
        public void SetUserDataInTable(string userId)
        {
            string strcon = "initial catalog=mydb;Data Source=192.168.0.15;password=ffsdfsf;user id=storeuser;";

            SqlConnection con = new SqlConnection(strcon);
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            con.Open();

            com.CommandText = string.Format("Select * from UserMasterTable WHERE UserID='{0}'", userId.Trim());
            SqlDataAdapter adap = new SqlDataAdapter(com);
            adap.Fill(UserDataTable);
        }

    }
}


Now, The form1 will have method to access method in above class to load data in datatable.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSetUserData_Click(object sender, EventArgs e)
        {
            UserClass objUser = new UserClass();
            objUser.SetUserDataInTable(txtUserId.Text.Trim());
        }

        private void btnGotoForm2_Click(object sender, EventArgs e)
        {
            if (UserClass.UserDataTable != null && UserClass.UserDataTable.Rows.Count > 0)
            {
                Form2 frm = new Form2();
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("Data is not loaded in User DataTable");
            }
        }
    }
}


You can load data saved in datatable from form2 as following:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestApp
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void btnLoadUserData_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = UserClass.UserDataTable;
        }
    }
}
   
The apparent answer would be using a singleton design pattern.

However, I don't want to present this opportunity as a perfect solution. First of all, this is not the best design pattern. It is quite possible to work without singletons even when you need to have some unique objects per application. The idea is: you can create some unique object as a local (stack) variable in your entry-point method (Main) and pass the reference to it in a chain to all other objects. It seems to be more bothersome than the singleton-based techniques, but can be more reliable. For example, you won't accidentally use it in non-UI threads and won't create cross-thread problems.

More importantly, System.Windows.Forms already provides a singleton, Application object. However, using its derived class would be inconvenient, by some pretty obvious reasons. You can uses another unique object of the type you need to derive from the .NET FCL class anyway — main form (you derive its class from the class Form). As this class is "de-facto" unique (unless you call Application.Run more than once, with different forms), you can put all unique database facilities in this class.

Moreover, for a really clean application design, you can develop a separate interface type which provides all this database functionality and implement this interface by your main form. To use it "anywhere in application", you can pass the interface instance to other forms and other objects, not the reference to the form. It will provide abstraction from the UI functionality present in form classes and yet provide a reference to a unique object, which is your form. (I hope you understand that the interface reference will serve as a compile-time type passed to all the parts of your application code, but the runtime type of the passed object will still be some form, only form-specific members will be not accessible to the code using the interface instance; which will perfectly suit your goals.)

Another aspect of this problem is isolation of the UI from other aspects of the application. In practice, you have to have separate UI layer, data layers, and other layers, such as "business logic". So, let's take a deeper look at the problems related to your question. I suggest you learn and analyze applicability of the following architectural patterns (http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)[^]):
MVVM — Model View View Model,
http://en.wikipedia.org/wiki/Model_View_ViewModel[^],

MVC — Model-View-Controller,
http://en.wikipedia.org/wiki/Model-view-controller[^]),

MVA — Model-View-Adapter,
http://en.wikipedia.org/wiki/Model–view–adapter[^],

MVP — Model-View-Presenter,
http://en.wikipedia.org/wiki/Model-view-presenter[^].
Pay attention for the motivation of those architectures. If you understand it, you would be able to create better design ideas.

—SA
   
Comments
Armel_Djient 15-May-16 16:53pm
   
thanks for ur reply. after reading MVC seems to be intersting
Sergey Alexandrovich Kryukov 15-May-16 18:53pm
   
You are welcome. Will you accept the answer formally?
—SA
It's very simple. If you want to fetch data from database only once and keep in datatable then you just need to create a static property of your DataTable and fill data in this data-table. If you want to query data only when you require it, you can just create a function of return type DataTable.

C#
public class MyClass
{
    public static DataTable MyDataTable { get; set; }

    //Access when you need///
    public DataTable GetMyDataTable()
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand com=new SqlCommand();
        com.Connection=con;
        con.Open();

        com.CommandText="Select * from tableA";
        SqlDataAdapter adap = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        adap.Fill(dt);
        return dt;
    }

    //Access when you need///
    public void SetDataInTable()
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand com = new SqlCommand();
        com.Connection = con;
        con.Open();

        com.CommandText = "Select * from tableA";
        SqlDataAdapter adap = new SqlDataAdapter(com);
        adap.Fill(MyDataTable);
    }


    //Access Like trhis
    public void GetInfo()
    {
        //If used static datatable propertu
        DataTable dt = MyClass.MyDataTable;

        //if function

        MyClass mc = new MyClass();
        DataTable dt1 = mc.GetMyDataTable();
    }


}
   
Comments
Armel_Djient 15-May-16 16:56pm
   
this is in the same class, how to do if i want to get that static datatable in other winform for example

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900