如何在winform应用程序中的任何位置访问数据表 [英] How to make datatable accessible anywhere in winform application

查看:52
本文介绍了如何在winform应用程序中的任何位置访问数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有视觉工作室2012 winform

i想让数据表可以访问我的应用程序中的任何地方:在每个winform中都可访问我将创建我的应用程序。



到目前为止,我已经从我的数据库表中填充了我的datagridview,并且所有这些获取的数据都存储在数据表中。

现在我想在任何地方访问这个数据表。



我尝试了什么:



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;

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;

解决方案

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);
        }

    }
}





现在,form1将有方法上述类中的访问方法,用于在datatable中加载数据。





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

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");
            }
        }
    }
}





您可以加载保存在数据表中的数据来自form2如下:





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

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;
        }
    }
}


明显的答案是使用单身设计模式



但是,我不想把这个机会作为一个完美的解决方案。首先,这不是最好的设计模式。即使您需要为每个应用程序提供一些独特的对象,也可以在没有单例的情况下工作。这个想法是:您可以在入口点方法( Main )中创建一个唯一对象作为本地(堆栈)变量,并将链中的引用传递给所有其他对象。它似乎比基于单例的技术更麻烦,但可以更可靠。例如,您不会在非UI线程中意外使用它,也不会产生跨线程问题。



更重要的是, System.Windows.Forms 已经提供了一个单例, Application 对象。但是,由于一些非常明显的原因,使用它的派生类会很不方便。您可以使用从.NET FCL类派生的另一个类型的唯一对象 - 主窗体(从类 Form 派生其类)。由于此类是事实上唯一的(除非您使用不同的表单多次调用 Application.Run ),您可以将所有唯一的数据库工具放在此类中。



此外,对于非常干净的应用程序设计,您可以开发一个单独的接口类型,它提供所有这些数据库功能并通过主窗体实现此接口。要在应用程序中的任何位置使用它,您可以将接口实例传递给其他表单和其他对象,而不是对表单的引用。它将提供表单类中存在的UI功能的抽象,并提供对唯一对象的引用,该对象是您的表单。 (我希望您理解,接口引用将作为传递给应用程序代码的所有部分的编译时类型,但运行时类型仍然是某种形式,只有特定于表单的成员才能使用接口实例访问代码;这完全符合您的目标。)



此问题的另一个方面是将UI与应用程序的其他方面隔离开来。实际上,您必须具有单独的UI层,数据层和其他层,例如业务逻辑。因此,让我们深入了解与您的问题相关的问题。我建议你学习和分析以下架构模式的适用性 http://en.wikipedia .org / wiki / Architectural_pattern_(computer_science) [ ^ ]):

MVVM - 模型视图模型,

http://en.wikipedia.org/wiki/Model_View_ViewModel [ ^ ],



MVC - 模型 - 视图 - 控制器,

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



MVA - 模型 - 视图-Adapter,

<小时ef =http://en.wikipedia.org/wiki/Model-view-adapter> http://en.wikipedia.org/wiki/Model-view-adapter [ ^ ],



MVP - 模型 - 视图 - 演示者,

http://en.wikipedia。 org / wiki / Model-view-presenter [ ^ ]。

注意这些架构的动机。如果您了解它,您将能够创建更好的设计理念。



-SA
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


这很简单。如果您只想从数据库中获取数据一次并保留在datatable中,那么您只需要创建DataTable的静态属性并填充此数据表中的数据。如果只想在需要时查询数据,可以创建返回类型DataTable的函数。



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.

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();
    }


}


这篇关于如何在winform应用程序中的任何位置访问数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆