PDA

View Full Version : مبتدی: یک سئوال ساده در مورد محل متغیر



vanidad
چهارشنبه 02 تیر 1389, 16:49 عصر
با سلام
من میخواهم یک متغیر تعریف کنم که در کل پیج دیده بشود پس آن را در قبلpage load و در زیر partial class مینویسم

string s;
حال سه دکمه هم دارم و میخواهم بازدن هر کدام یک مقدار به مقدار قبلی این متغیر اضافه شود
اما با هربار زدن هر یک از دکمه ها و پست بک شدن صفحه دوباره این خط تعریف متغیر هم اجرا میشود و مقدارش 0 میگردد و هیچ گاه نمی توانم مقدار جدید را به آن اضافه کنم.
حالا چه کنم؟

ricky22
چهارشنبه 02 تیر 1389, 17:06 عصر
سلام با هر postback مقدار صفر میشه باید از viewstate استفاده کنی

[

LTR_INLINE]using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class FileReader : System.Web.UI.Page
{


string FormStatus;
private void Page_Load(System.Object sender, System.EventArgs e)
{
//Upon first visit to the page, FormStatus is populated with an appropriate value
if (!Page.IsPostBack) {
FormStatus = "InitialLoad";
lblFormStatus.Text = FormStatus;
//If the page is being posted back we grab the value from ViewState and put it in FormStatus
} else {
FormStatus = ViewState("FormStatus");
}
}

private void Page_PreRender(object Sender, EventArgs E)
{
//Just before the page loads and after all other processing is done (which may have changed)
//our FormStatus variable value, we make sure that it gets put back into the ViewState variable
ViewState("FormStatus") = FormStatus;
}

private void btnFormStatusChange_Click(System.Object sender, System.EventArgs e)
{
//Click routine from a test button on page to force value change on click
//Test label on page just to show us that it worked
FormStatus = "AddNew";
lblFormStatus.Text = FormStatus;
}
public FileReader()
{
Load += Page_Load;
}
}
[/LTR_INLINE]