值没有正确传递给其他形式

时间:2013-10-11 13:24:56

标签: c# winforms arguments

我的程序不会正确地将值从一个表单传递到另一个表单,当它将字符串传递给下一个表单时,它总是显示为null,说

这是相关领域的代码:

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?

1 个答案:

答案 0 :(得分:2)

只需将连接字符串注入loginForm

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

然后是:

new SqlCeConnection(_cString))

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

... new loginForm(databaseselected);