0

所以我在做一个数据库项目,在我的第一个表单中,我有访问我的数据源的 sql 连接命令。我还创建了一个数据集,这一切都在我的显示表单中

显示表单用于显示数据库,我添加了一个按钮来添加记录,所以当我单击添加记录时,它会转到添加表单,我可以在其中填写详细信息以创建新联系人。然后返回第一个表单以显示新创建的联系人和所有其他联系人。

但是我遇到了一些问题,因为数据集需要与显示表单中的数据集相同。

如何使我的所有表单中的数据集都相同?

更新:

所以我所做的是在我的 Program.cs 中我在那里创建了对象......并将它们设为公共静态。

public static DataSet ds = new DataSet();

所以然后在我的addcontact表单中我可以这样称呼它......

Program.ds.Clear();

与我的数据适配器/绑定源和 sql 连接相同。这可以吗?

4

2 回答 2

3

Well, you have several conceptual options. You seem to be thinking of giving access to the data set to the child form, which is certainly something that you could do, but in my eyes it would make sense for the child form to provide the information for a single record to the parent form. The child form doesn't need to know anything about the dataset, or all of the other records.

In general you should try to limit information so that it is only avaliable where it is needed; you'll reduce the possibility of bugs that way. It would be bad practice to just make the dataset a global variable, which is what making it public and static is doing. By doing that not only are you providing the entire set of data to the child form (and also letting it be modfied) but your letting the data be read or modified from anywhere in the entire program. That's just asking for trouble.

The general idea will likely look something like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 childForm = new Form2();
        childForm.ShowDialog();
        string name = childForm.Name;
        string value = childForm.SomeOtherValue;
        //you can stick these properties in your dataset here.
    }
}

public partial class Form2 : Form
{
    private TextBox textbox1;
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Close();
    }

    public string Name { get { return textbox1.Text; } }
    public string SomeOtherValue { get { return "12345"; } }
}
于 2012-07-24T16:02:25.040 回答
3

创建一个数据集类,通过构造函数向每个表单添加传递..“Class = Class”进行引用..而不是副本。( DataSet 是一个类...)

public partial class Form1 : Form
{
DataSet _dataset;

public Form1(DataSet dataSet)
{
    _dataset = dataset;
    InitializeComponent();
}
//..

public partial class Form2 : Form
{
DataSet _dataset;

public Form2(DataSet dataSet)
{
    _dataset = dataset;
    InitializeComponent();
}
//..


static class Program
{
    static void Main()
    {
        DataSet DS = new DataSet();

        Application.Run(new Form1(DS));
    }
}
于 2012-07-24T16:23:08.930 回答