我正在尝试使用类中的按钮单击设置公共 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]; }您可以看到我正在尝试跨班级转移 ID。数据库插入很好,但它的 ID 插入了“0”。
3 回答

杨__羊羊
TA贡献1943条经验 获得超7个赞
如果要保留以前的值,可以在Index类中使用静态字段
public static int ID1;
这就是你如何在类之外设置它的值
Index.ID1 = 23;

qq_笑_17
TA贡献1818条经验 获得超7个赞
我无法通过您提供的代码看到这一点,但根据您的描述,您正在执行 bLogin_Click 方法,然后创建一个新的 Index 实例。
这个新实例的 ID1 的值默认为 0(除非您在我看不到的构造函数中设置它)。所以你需要先创建实例,然后在那个实例上执行 bLogin_Click 。
看起来您也为 Result2 分配了一个值,但随后对 Result 执行了验证。
此外,并不是真正相关,但许多人认为类包含公共字段是不好的做法,您应该考虑使用属性,甚至是这样的基本属性:
public int ID1 { get; private set; }

蓝山帝景
TA贡献1843条经验 获得超7个赞
每当创建新实例时,默认构造函数都会触发。没有任何参数的构造函数称为默认构造函数;换句话说,这种类型的构造函数不带参数。默认构造函数的缺点是类的每个实例都将被初始化为相同的值,并且不可能将类的每个实例初始化为不同的值。
默认构造函数初始化:
类中的所有数字字段为零。 所有字符串和对象字段为 null。
如果您想为所有消费者/客户端或跨多个实例维护类型和值的状态,只需将其设置为静态类型。
- 3 回答
- 0 关注
- 186 浏览
添加回答
举报
0/150
提交
取消