尝试从另一种形式获取字符串,但是我得到的字符串值为null

时间:2018-12-10 19:09:47

标签: c#

我的第一个表单上有comboBox1,comboBox2和一个textBox。当我单击此表单上的按钮时,我试图将文本值从此项目发送到第二个表单,并在我的连接字符串中使用此值。我将文本框和组合框的值保存在表格2中的字符串中。 到目前为止,我已经做到了,但是第二种形式的值似乎为空:

 //first form
 private void button1_Click(object sender, EventArgs e)
 {
    Form1 f2 = new Form1();
    f2.Text = comboBox2.Text;

    Form1 f3 = new Form1();
    f3.Text = comboBox1.Text;

    Form1 f4 = new Form1();
    f4.Text = textBox1.Text;

string selectedUser = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);

         if ((selectedUser == "admin") && (textBox1.Text == "password"))
        {
            Form1 form3 = new Form1();
            form3.Show();
            form3.Activate();
            this.Hide();
        }

}
//second form
public partial class Form1 : Form                  
{
    private string text1;
    public string Text1
    {
        get { return text1; }
        set { Text1 = value; }
    }

    private string text2;
    public string Text2
    {
        get { return text2; }
        set { text2 = value; }
    }

    private string text3;
    public string Text3
    {
        get { return text3; }
        set { text3 = value; }
    }

    public Form1(Form1 frm1)
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        string db = Text1;
        string user = Text2;
        string pass = Text3;

        String strConnection = @"Data Source=SERVER;Initial Catalog ="+db+"; User ID ="+user+"; Password ="+pass+";";
        SqlConnection con = new SqlConnection(strConnection);

        try
        {
            con.Open();
            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.Connection = con;
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "Select table_name  from information_schema.tables";
            SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
            DataTable dtRecord = new DataTable();
            sqlDataAdap.Fill(dtRecord);
            dtRecord.DefaultView.Sort = "table_name ASC";
            ComboBox1.DataSource = dtRecord;
            ComboBox1.DisplayMember = "TABLE_NAME";
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }

    }

1 个答案:

答案 0 :(得分:1)

  1. 您正在创建Form1的三个实例,我认为这不是故意的。

  2. 您正在设置新实例的Text属性,而不是自定义属性。

解决方案:将button1_Click的正文替换为以下内容:

private void button1_Click(object sender, EventArgs e)
{
    var nextForm = new Form1();
    nextForm.Text1 = comboBox2.Text;
    nextForm.Text2 = comboBox1.Text;
    nextForm.Text3 = textBox1.Text;

    string selectedUser = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);

    if ((selectedUser == "admin") && (textBox1.Text == "password"))
    {
        nextForm.Show();
        nextForm.Activate();
        this.Hide();
    }
}