Maintaining temporary table in ASP.NET
What --
To create a variable with table-like structure and to store the
information within it. And to retains the records with page postbacks.
Why -- The need of temporary table may be necessary if you don't want to interact with the database as and when you need it. Rather you prefer storing all information in some intermediate variable and on certain conditions to synchronize these data with the database. It will increase your execution speed causing faster application loading which will give the end user more comfort and satisfaction. |
How --
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // To add Autoincremented column to the table. DataColumn dcSlno = new DataColumn("PK_ID"); dcSlno.AutoIncrement = true; dcSlno.AutoIncrementSeed = 0; dcSlno.AutoIncrementStep = 1; dcSlno.DataType = typeof(Int32); dtTemp.Columns.Add(dcSlno); // To add column with the default value. DataColumn points = new DataColumn(); points.ColumnName = "POINTS"; points.DataType = typeof(Int32); points.DefaultValue = 1; dtTemp.Columns.Add(points); // If you want to add data from the database DataTable dtDatabase = null; // Fetch Data from database dtTemp = dtDatabase.Clone(); dtTemp.Merge(dtDatabase); // TO insert SPecific rows to temp table. // ! note -- The structure of row must be matched with the structure of temporary rable. dtTemp.ImportRow(dtDatabase.Rows[0]); //Updation :: dtTemp.Rows[0].SetField<int>("POINTS", 20); // Deleation of record. dtTemp.Rows[1].Delete(); //Filteration of records. string Expression = "POINT > 20"; string sort = "SLNO ASC"; DataRow[] drFiltered = dtTemp.Select(Expression, sort); foreach (DataRow dr in drFiltered) { dtTemp.ImportRow(dr); }
//Another approach for filtering the contents , But execution time is
more , so only acceptable for smaller amount of datarows.
DataView dv = new DataView(dtTemp); dv.Sort = ("SLNO"); dtTemp = dv.ToTable(); // Storing of records during page postback.. //One idea can be to store this table in viestate and retrive values from the viewstate each time.
ViewState["TempTable"] = dtTemp;
//Bind to the databinding control
ListView1.DataSource = dtTemp; ListView1.DataBind(); } if (Page.IsPostBack) { // On each postback retrive the datatable from the view state if (ViewState["TempTable"] != null) { dtTemp = (DataTable)ViewState["TempTable"]; } //Bind to the databinding control ListView1.DataSource = dtTemp; ListView1.DataBind(); } Note: The above approach should not be taken when working with large number of records as it may adversely affect performance // Create a temporary datatable. DataTable dtTemp = new DataTable(); |
0 comments: