首页 > 解决方案 > 试图从另一个表单中获取一个字符串,但我得到字符串值 null

问题描述

我的第一个表单上有comboBox1、comboBox2 和一个文本框。当我点击这个表单上的一个按钮时,我试图将一个文本值从这个项目发送到第二个表单,并在我的连接字符串中使用这个值。我将文本框和组合框的值保存在表单 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);

        }

    }

标签: c#

解决方案


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

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

解决方案:将 body 替换为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();
    }
}

推荐阅读