首页 > 解决方案 > Public Int 在不同的类中使用时显示为 0

问题描述

我正在尝试使用类中的按钮单击设置公共 int,然后使用创建新实例并使用另一个类中的值然后将其插入数据库。

我正在使用 webforms 和 C# 来生成我的系统。对此的任何帮助都非常感谢。

1 级--------------------------------

 public partial class Index : System.Web.UI.Page
    {

        public int ID1;

        public void bLogin_Click(object sender, EventArgs e)
        {
            string username = tbUsername.Text;
            string password = tbPassword.Text;

            SqlCommand cmd2 = new SqlCommand("select UsersID from [dbo].[Users] where Username=@uname and Password=@password");
            cmd2.Connection = con;
            cmd2.Parameters.AddWithValue("@uname", tbUsername.Text);
            cmd2.Parameters.AddWithValue("@password", tbPassword.Text);

            int Result2 = (int)cmd2.ExecuteScalar();
            ID1 = Result2;

            if (Result > 0)
            {
                MessageBox.Show("Welcome");
                MessageBox.Show(ID1.ToString());
                Response.Redirect("Dashboard.aspx");
                con.Close();

            }
            else
            {
                MessageBox.Show("Incorrect");
            }

        }

       }
}

第 2 类 -----------------------------------

protected void bSubmit_Click(object sender, EventArgs e)
        {

            SQLDatabase.DatabaseTable module_table = new SQLDatabase.DatabaseTable("Boards");   // Need to load the table we're going to insert into.

            SQLDatabase.DatabaseRow new_row = module_table.NewRow();    // Create a new based on the format of the rows in this table.


            Index index = new Index();
            string new_id = module_table.GetNextIDBoards().ToString();    // Use this to create a new ID number for this module. This new ID follows on from the last row's ID number.
            string title = tbTitle.Text;
            string body = tbContent.Text;
            DateTime now = DateTime.Now;
            string date = now.GetDateTimeFormats('d')[0];
            string time = now.GetDateTimeFormats('t')[0];

            new_row["BoardsID"] = new_id;                                 // Add some data to the row (using the columns names in the table).
            new_row["Title"] = title;
            new_row["Body"] = body;  // Module name.
            new_row["UsersID"] = index.ID1.ToString();
            new_row["DateCreated"] = date;
            new_row["TimeCreated"] = time;

            module_table.Insert(new_row);                           // Execute the insert - add this new row into the database.

            MessageBox.Show("New Board Created");
            Response.Redirect("Dashboard.aspx");


        }

您可以看到我正在尝试跨班级转移 ID。

数据库插入很好,但它的 ID 插入了“0”。

标签: c#htmlvisual-studio

解决方案


每当创建新实例时,默认构造函数都会触发。没有任何参数的构造函数称为默认构造函数;换句话说,这种类型的构造函数不带参数。默认构造函数的缺点是类的每个实例都将被初始化为相同的值,并且不可能将类的每个实例初始化为不同的值。

默认构造函数初始化:

类中的所有数字字段为零所有字符串和对象字段为 null

如果您想为所有消费者/客户端或跨多个实例维护类型和值的状态,只需将其设置为静态类型。


推荐阅读