1

我的程序不会将值从一种形式正确传递到另一种形式,当它将字符串传递到下一种形式时,它总是显示为空,说

这是我在相关领域的代码:

public partial class openingForm : Form
{
    public string databaseselected;
    public openingForm()
    {
        InitializeComponent();
    }

    public void button2_Click(object sender, EventArgs e)
    {
        openFileDialog1.Filter = "Event Control Database Files (.sdf)|*.sdf";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.ShowDialog();
        databaseselected = openFileDialog1.FileName;
        loginForm login1 = new loginForm();
        this.Hide();
        login1.ShowDialog();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        string name = textBox1.Text.Trim();
        if (!File.Exists(textBox1.Text.Trim()+".sdf"))
        {
            string connectionString = "DataSource= "+name+".sdf";
            databaseselected = connectionString;**
            SqlCeEngine en = new SqlCeEngine(connectionString);
            en.CreateDatabase();

然后创建一些表......然后:

            loginForm login = new loginForm();
            login.ShowDialog();
            this.Close();

到目前为止,我们有一个在开始时声明的变量,并根据单击的按钮初始化为不同的值。这是下一种形式:

public partial class loginForm : Form
{
    openingForm op = new openingForm();
    public string userLoggedIn;
    public loginForm()
    {
        InitializeComponent();
    }

    private void loginForm_Load(object sender, EventArgs e)
    {

        AddValueToLogs();

    }

    private string myMethod(string user, string pass)
    {
        string selection = "Select * from Login where userName = @userName and Hash=@hashResult";
        using (var myConnection = new SqlCeConnection(**op.databaseselected**))
        using (var command = new SqlCeCommand(selection, myConnection))
        {
            command.Parameters.Add("@username", SqlDbType.NVarChar, 20).Value = userNameBox.Text;
            command.Parameters.Add("@hashResult", SqlDbType.NVarChar, 50).Value = hashResult;

谁能告诉我为什么数据库选择的值没有传递给 loginForm?

4

1 回答 1

2

只需将连接字符串注入loginForm

private string _cString;
public loginForm(string cString)
{
    _cString = cString;
}

然后稍后:

new SqlCeConnection(_cString))

因此,当您启动时loginForm,请执行以下操作:

... new loginForm(databaseselected);
于 2013-10-11T13:29:27.570 回答