我尝试使用DATATABLE存储整个应用程序的值。我没有使用任何数据库永久存储值。这是我可以在整个应用程序中使用的虚拟值。
问题实际上是每当我向DATATABLE添加新行值时,它只会覆盖DATATABLE中的先前值,而不是添加新行。
是否有机会动态地向DATATABLE添加多行,我可以在整个应用程序会话中使用它。
**我的注册页面**
public partial class _Default : System.Web.UI.Page
{
DataTable myDataTable;
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi@gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri@gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani@gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
if (!IsPostBack)
{
if (Session["name"] != null)
{
myDataTable = Session["name"] as DataTable;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
myDataTable.Rows.Add(new object []{ TextBox1.Text ,TextBox2.Text,TextBox3.Text , TextBox4.Text,TextBox5.Text ,TextBox6.Text });
HttpContext.Current.Session["name"] = myDataTable;
if (Session["name"] != null)
{
Response.Write("success");
}
}
我的登录页面
public partial class login : System.Web.UI.Page
{
DataTable dtResult;
protected void Page_Load(object sender, EventArgs e)
{
dtResult = (DataTable)Session["name"];
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dtResult.Rows.Count; i++)
{
string un = dtResult.Rows[i].Field<string>("username");
string fn = dtResult.Rows[i].Field<string>("password");
if (TextBox1.Text == un && TextBox2.Text == fn)
{
//Response.Write("success");
Response.Redirect("home.aspx");
}
}
}
答案 0 :(得分:3)
<强>问题:强>
每Postback
您创建一个新datatable
并将其覆盖到上一个{<1}}:
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
//....
HttpContext.Current.Session["name"] = myDataTable; //overriding to the previous
因此,当您单击按钮添加新行时,它会回发并重新创建新数据表,然后向该表添加新行。
<强>解决方案:强>
您只需要修改Page_Load
事件处理程序:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null) //this is you have to do at every postback
{
myDataTable = Session["name"] as DataTable;
}
if (!IsPostBack)
{
//if it is not post back, create a new DataTable and add values to it
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi@gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri@gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani@gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
}
}