c# - 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”。
解决方案
每当创建新实例时,默认构造函数都会触发。没有任何参数的构造函数称为默认构造函数;换句话说,这种类型的构造函数不带参数。默认构造函数的缺点是类的每个实例都将被初始化为相同的值,并且不可能将类的每个实例初始化为不同的值。
默认构造函数初始化:
类中的所有数字字段为零。 所有字符串和对象字段为 null。
如果您想为所有消费者/客户端或跨多个实例维护类型和值的状态,只需将其设置为静态类型。
推荐阅读
- python - Hadoop Streaming 无法运行 python
- javascript - 如何将值传递给 sweetalert?
- android - 如何在 Android Xamarin.Forms 中获取附近 WiFi 网络的列表?
- outlook - 自动将发送电子邮件另存为 Adobe PDF 并保存在文件夹中
- python - 如何在元组列表中选择具有特定值的元素
- java - 对 CSV 文件中的重复项进行分组并根据某些值对数据进行排名
- python - 无法在熊猫python中删除CSV中具有不同表格格式的行
- ceph - 为什么 Ceph 通过对象哈希而不是 CRUSH 算法计算 PG ID?
- for-loop - 将像素从图像处理为黑色图像以通过最近邻放大
- asp.net - 每当尝试向本地托管的 API 发送 GET 请求时,邮递员都会坚持发送请求