How to insert an array of String in SQLite database in blackberry - sqlite

I have a Database Manager class which is creating the SQLite Database.Now from another class, i am creating the instance of that class. Now how can i insert an array of string in the Database?
My Database Manager class code is like below:
public class DatabaseManager
{
public Database sqliteDb = null;
public DatabaseManager()
{
try
{
URI myURI = URI.create("/SDCard/databases/itemdb.db");
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement statement = sqliteDb.createStatement("CREATE TABLE if not exists SelectedItem (Name TEXT, Quantity TEXT)");
statement.prepare();
statement.execute();
statement.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(sqliteDb!=null)
{
sqliteDb.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void insertValues(String tableName, Hashtable ht)
{
try
{
Logger.out("Grocery", "it is comin here");
URI myURI = null;
try
{
myURI = URI.create("/SDCard/databases/itemdb.db");
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (MalformedURIException e)
{
e.printStackTrace();
}
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement dbStatement = sqliteDb.createStatement("INSERT INTO SelectedItem(Name,Quantity) " + "VALUES (?,?)");
Enumeration itemName = ht.keys();
Enumeration itemQty = ht.elements();
while(itemName.hasMoreElements())
{
Logger.out("Grocery", "more items");
String strName = itemName.nextElement().toString();
String strQty = itemQty.nextElement().toString();
Logger.out("Grocery", "name:" + " " + strName);
Logger.out("Grocery", "QTY:" + " " + strQty);
dbStatement.bind(1, strName);
dbStatement.bind(2, strQty);
Logger.out("Grocery", "Binded:::::::::");
dbStatement.execute();
dbStatement.reset();
Logger.out("Grocery", "Executed:::::::::");
}
dbStatement.close();
}
catch (DatabaseException e)
{
e.printStackTrace();
}
}
public void closeDb()
{
try
{
sqliteDb.close();
}
catch (DatabaseIOException e)
{
e.printStackTrace();
}
}
}
Now i am taking the name and quantity as a hash table. And in my main class, when i am pressing the button i am inserting the values in the database like below:
dbManager = new DatabaseManager();
dbManager.insertValues("SelectedItem", htItem);

Try this as following when ever you want to use another class method as globle then just declare it as static . genaral query for multiple row insertion is
INSERT INTO 'tablename' SELECT 'data1' AS 'column1', 'data2' AS
'column2' UNION SELECT 'data3', 'data4' UNION SELECT 'data5', 'data6'
UNION SELECT 'data7', 'data8'
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class SampleDatabase extends UiApplication
{
LabelField test;
String names[];
int ages[];
MainScreen screen = new MainScreen();
public static void main(String[] args)
{
SampleDatabase theApp = new SampleDatabase();
theApp.enterEventDispatcher();
}
public SampleDatabase()
{
ButtonField btn=new ButtonField("Click");
names=new String[10];
ages=new int[10];
for(int i=0;i<10;i++)
{
names[i]="Govind"+i;
ages[i]=i;
}
btn.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
synchronized (UiApplication.getEventLock()) {
databaseOperations.DatabaseManager();
databaseOperations.InsertDatabaseManager(names,ages);
}
}
});
screen.add(btn);
pushScreen(screen);
}
}
This is another class named as "databaseOperations.java"
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;
public class databaseOperations {
public static void DatabaseManager()
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
Statement s = d.createStatement( "CREATE TABLE if not exists 'People' ( " +
"'Name' TEXT, " +
"'Age' INTEGER )");
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void InsertDatabaseManager(String[] names,int ages[])
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
String query="INSERT INTO 'People' SELECT '"+names[0]+"' AS 'Name', "+ages[0]+" AS 'Age'";
String query2="";
for(int i=1;i<names.length;i++)
{
query2=query2+" UNION SELECT '"+names[i]+"', "+ages[i];
}
System.out.println(query+query2);
Statement s = d.createStatement(query+query2);
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Related

How can we insert date into the SQLite database

For each data insert in SQLite database, I would like to get insert the current Date as well. How can I do it in Xamarin Forms app ?
Below is my code which now insert some status data into the database.
public void OnOKButtonClicked(object sender, EventArgs e)
{
overlay.IsVisible = false;
DisplayAlert("Result",
string.Format("You entered {0}", EnteredStatus.Text), "OK");
SoccerAvailability soccerAvailability = new SoccerAvailability();
soccerAvailability.SoccerStatus = EnteredStatus.Text;
var dailySoccerStatus = EnteredStatus.Text;
int x = 0;
try
{
if (!string.IsNullOrWhiteSpace(EnteredStatus.Text))
{
//Insert the soccer status to the database:
x = conn.Insert(soccerAvailability);
}
else
{
DisplayAlert("Soccer Availability", "Availability cannot be left blank", "OK");
}
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
Navigation.PushAsync(new Settings(soccerAvailability));
}
DisplaySoccerStatus();
}
just create a CurrentDate DateTime property on your SoccerAvailability model
soccerAvailability.CurrentDate = DateTime.Now;
x = conn.Insert(soccerAvailability);

windows forms, async task exception catching

I have a form, 2 buttons , 1 textbox. Button 1 processes the TaskException_click.
What I wanted to do is understanding the async task/void difference. But checking multiple examples I still do not understand or get it to work. Below my code.
When I click the taskexception button, the unobservedtaskexception is not executed (I expected that).
When I click it another time, the event is executed with the exception of the first click. However the UI is not updated (actually it hangs). Would like to know what I am doing wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class main : Form
{
public main()
{
InitializeComponent();
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
//textBox1.Text = "Unobserved Exception caught ";
e.SetObserved();
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate()
{
//codes to do whatever i wan to do with the GUI
//Examples of it would be disposing a flowlayout panel
//and re-adding it back and populating it again to
//show the refreshed values.
textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
});
}
else
{
textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
}
}
private int i = 0;
// Add async here! You can always add these to events
private async void TaskException_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
Task t = TaskThrowAnException();
textBox1.Text = "done";
t = null;
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
catch (Exception ex)
{
textBox1.Text = "Exception caught";
}
}
private async Task TaskThrowAnException()
{
//await Task.Delay(1000);
i++;
throw new Exception("Task" + i.ToString());
}
private async void VoidException_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
VoidThrowAnException();
textBox1.Text = "done";
}
catch (Exception ex )
{
textBox1.Text = "Exception caught";
}
}
private async void VoidThrowAnException()
{
//await Task.Delay(1000);
throw new Exception("Void");
}
}
}
For the TaskException case the exception is stored in the Task this is the expected behavior for async methods returning Task. If you want the exception to be thrown you need to observe the exception by awaiting the Task or calling Result or Wait() on the Task.
If the exception is unobserved it should get thrown when the Task is finalized, the only thing I can conclude is that somehow the task is not being finalized when you call
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
I am nor sure why the local variable is not GCed, if add another button and you put the code above in the button handler (e.g Clear_Click) everything works as expected. I thought the generated code must somehow have a link to the task variable but I couldn't find any link.
Here is the generated code from Reflector:
namespace WindowsFormsApplication1
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
public class Form1 : Form
{
private IContainer components = null;
private int i = 0;
private Button TaskException;
private TextBox textBox1;
private Button VoidException;
public Form1()
{
this.InitializeComponent();
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(this.TaskScheduler_UnobservedTaskException);
}
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.textBox1 = new TextBox();
this.TaskException = new Button();
this.VoidException = new Button();
base.SuspendLayout();
this.textBox1.Location = new Point(13, 13);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new Size(0x20d, 0x13f);
this.textBox1.TabIndex = 0;
this.TaskException.Location = new Point(13, 0x16d);
this.TaskException.Name = "TaskException";
this.TaskException.Size = new Size(0x9b, 0x17);
this.TaskException.TabIndex = 1;
this.TaskException.Text = "TaskException";
this.TaskException.UseVisualStyleBackColor = true;
this.TaskException.Click += new EventHandler(this.TaskException_Click);
this.VoidException.Location = new Point(0xda, 0x16d);
this.VoidException.Name = "VoidException";
this.VoidException.Size = new Size(0xab, 0x17);
this.VoidException.TabIndex = 2;
this.VoidException.Text = "VoidException";
this.VoidException.UseVisualStyleBackColor = true;
this.VoidException.Click += new EventHandler(this.VoidException_Click);
base.AutoScaleDimensions = new SizeF(6f, 13f);
base.AutoScaleMode = AutoScaleMode.Font;
base.ClientSize = new Size(550, 430);
base.Controls.Add(this.VoidException);
base.Controls.Add(this.TaskException);
base.Controls.Add(this.textBox1);
base.Name = "Form1";
this.Text = "Form1";
base.ResumeLayout(false);
base.PerformLayout();
}
[DebuggerStepThrough, AsyncStateMachine(typeof(<TaskException_Click>d__4))]
private void TaskException_Click(object sender, EventArgs e)
{
<TaskException_Click>d__4 d__;
d__.<>4__this = this;
d__.sender = sender;
d__.e = e;
d__.<>t__builder = AsyncVoidMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<TaskException_Click>d__4>(ref d__);
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
MethodInvoker method = null;
e.SetObserved();
if (base.InvokeRequired)
{
if (method == null)
{
method = (MethodInvoker) (() => (this.textBox1.Text = "Unobserved Exception caught " + e.Exception.Message));
}
base.BeginInvoke(method);
}
else
{
this.textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
}
}
[AsyncStateMachine(typeof(<TaskThrowAnException>d__6)), DebuggerStepThrough]
private Task TaskThrowAnException()
{
<TaskThrowAnException>d__6 d__;
d__.<>4__this = this;
d__.<>t__builder = AsyncTaskMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<TaskThrowAnException>d__6>(ref d__);
return d__.<>t__builder.Task;
}
[DebuggerStepThrough, AsyncStateMachine(typeof(<VoidException_Click>d__8))]
private void VoidException_Click(object sender, EventArgs e)
{
<VoidException_Click>d__8 d__;
d__.<>4__this = this;
d__.sender = sender;
d__.e = e;
d__.<>t__builder = AsyncVoidMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<VoidException_Click>d__8>(ref d__);
}
[AsyncStateMachine(typeof(<VoidThrowAnException>d__a)), DebuggerStepThrough]
private void VoidThrowAnException()
{
<VoidThrowAnException>d__a _a;
_a.<>4__this = this;
_a.<>t__builder = AsyncVoidMethodBuilder.Create();
_a.<>1__state = -1;
_a.<>t__builder.Start<<VoidThrowAnException>d__a>(ref _a);
}
[CompilerGenerated]
private struct <TaskException_Click>d__4 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
public EventArgs e;
public object sender;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.textBox1.Text = "";
try
{
Task task = this.<>4__this.TaskThrowAnException();
this.<>4__this.textBox1.Text = "done";
task = null;
}
catch (Exception)
{
this.<>4__this.textBox1.Text = "Exception caught";
}
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
catch (Exception exception2)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception2);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <TaskThrowAnException>d__6 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncTaskMethodBuilder <>t__builder;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.i++;
throw new Exception("Task" + this.<>4__this.i.ToString());
}
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <VoidException_Click>d__8 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
public EventArgs e;
public object sender;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.textBox1.Text = "";
try
{
this.<>4__this.VoidThrowAnException();
this.<>4__this.textBox1.Text = "done";
}
catch (Exception)
{
this.<>4__this.textBox1.Text = "Exception caught";
}
}
}
catch (Exception exception2)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception2);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <VoidThrowAnException>d__a : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
SynchronizationContext current = SynchronizationContext.Current;
throw new Exception("Void");
}
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
}
}

Datatype mismatch for blob type blackberry

I have an exception that Datatype mismatch in this line
byte[] _data = (byte[])row.getBlobBytes(1);
and in the table I have the type of column 2 is BLOB.
public static UrlRsc getContentUrl(String name) {
UrlRsc elementRsc = null;
try {
Statement statement = DB
.createStatement("SELECT * FROM table where"
+ " Name='"
+ name + "'");
statement.prepare();
Cursor cursor = statement.getCursor();
Row row;
while (cursor.next()) {
row = cursor.getRow();
byte[]_data;
_data = row.getBlobBytes(1);
}
statement.close();
cursor.close();
} catch (DatabaseException dbe) {
System.out.println(dbe.toString());
} catch (DataTypeException dte) {
System.out.println(dte.toString());
}
return elementRsc;
}
Can any one help me ?
Hi i am using following code for save image in my local database and i got success. i just posted my 3 methods
Note: When i am inserting image into data base i changed that image in byte array then only i can save into that table
1)Table creation 2) table insertion 3)image retrieving from table
ContactImage_table creation
public ContactImageTableCreation(){
try{
Statement stmt=DATABASE.createStatement("create table if not exists 'ContactImage_table'(ID 'TEXT',image 'blob',NodeId 'TEXT')");
stmt.prepare();
stmt.execute();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Insert data into ContactImage_table
public void ContactImageTableInsertion(){
try{
Statement st=DATABASE.createStatement("insert into ContactImage_table (ID,Image,NodeId)values(?,?,?)");
st.prepare();
st.bind(1, "101");
st.bind(2, BYTE_ARRY);
st.bind(3,"103");
st.execute();
st.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
Retrieving data from ContactImage_table
public ContactImageTableDataRetriving(){
try{
Statement st=DATABASE.createStatement("select * from ContactImage_table");
st.prepare();
Cursor c=st.getCursor();
Row r;
int i=0;
while(c.next()){
r=c.getRow();
i++;
// ContactImageObject is a wrapper class for data handling
contactImageObj=new ContactImageObject();
contactImageObj.setId(r.getString(0));
byte[] decoded=r.getBlobBytes(1);
EncodedImage fullImage = EncodedImage.createEncodedImage(decoded, 0, decoded.length);
Bitmap b=fullImage.getBitmap();
contactImageObj.setImage(b);
// System.out.println("Successfully retrived");
if(i==0){
// System.out.println("No Records");
}
}
st.close();
}catch (Exception e) {
// System.out.println(e.getMessage());
}
}
just cross check your code with this code snippet hope you will get resolve all the best

SqLite installation with blackberry JDE

I have installed Blackberry JDE and Eclipse. I want to create a SqLite database for my application. Should I install SqLite separately or does it come with BlackBerry JDE?
There is nothing to install separate for sqlite database. You have to create it programmatically and have to work with it. Use this.
Creating Database in SD Card :
Public void CreateDatabase()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.create(myURI);
d.close();
add(new RichTextField("DB created successfully"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Creating Table in Database:
Public void CreateTable()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/"+"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement( "CREATE TABLE 'testtable' ( " +"'id' INTEGER, " +"'name' TEXT ");
st.prepare();
st.execute();
st.close();
d.close();
add(new RichTextField("Table created successfully"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Inserting data’s in Table:
Public void InsertData ()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("INSERT INTO testtable(id,name) " + "VALUES (1,’Arun’)");
st.prepare();
st.execute();
st.close();
d.close();
add(new RichTextField("Values Inserted"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Retrieving Values from Database:
Public void RetriveValues()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT id,name FROM testtable");
st.prepare();
net.rim.device.api.database.Cursor c = st.getCursor();
Row r;
int i = 0;
while(c.next())
{
r = c.getRow();
i++;
add(new RichTextField(i + ". ID = " + r.getInteger(0)
+ " , "
+". Name = " + r.getString(1)));
}
if (i==0)
{
add(new RichTextField("No data in the table."));
}
st.close();
d.close();
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}

ASP.NET: How to persist Page State accross Pages?

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?
If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

Resources