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);
}
}
}
}
Related
I have a FileSystemWatchers monitoring 1 location in a Start/stop Button, but I canĀ“t manage to stop it, the button works pretty much well as when I click on it, it reads the code when it is off (the text changes to "start Watching") but it does not manage to stop monitoring, also I have tried "watcher.EnableRaisingEvents = false;" but it does not work could you please help me??
using System
using System.ComponentModel
using System.Diagnostics
using System.Drawing
using System.IO
using System.Windows.Forms
namespace Watcher
{
public partial class Form1 : Form
{
private bool isWatching
bool on = true
bool togglelight = true
Timer t = new Timer()
public Form1()
{
InitializeComponent()
}
private void button1_Click(object sender, EventArgs e)
{
if (isWatching)
{
stopWatching()
}
else
{
startWatching()
}
}
private void startWatching()
{
isWatching = true
button1.Text = "Stop Watching"
t.Start()
on = false;
var watcher = new FileSystemWatcher(#"C:\location1")
watcher.NotifyFilter = NotifyFilters.CreationTime
| NotifyFilters.CreationTime
| NotifyFilters.FileName
watcher.Changed += OnChanged
watcher.Error += OnError
watcher.Filter = "*.xlsx"
watcher.IncludeSubdirectories = false
watcher.EnableRaisingEvents = true
private void stopWatching()
{
isWatching = false;
button1.Text = "Start Watching"
button1.BackColor = Color.Gray
t.Enabled = false
t.Stop()
on = true
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return
}
Console.WriteLine(DateTime.Now + " tipo de cambio: " +
e.ChangeType + ". " + e.FullPath)
kNime_Bat(#" C:\Users\BAT\Knime_eSTORE.bat")
Console.WriteLine(DateTime.Now + " se proceso correctamente")
}
private static void OnError(object sender, ErrorEventArgs e) =>
PrintException(e.GetException())
private static void PrintException(Exception ex)
{
if (ex != null)
{
Console.WriteLine($"Message: {ex.Message}")
Console.WriteLine("Stacktrace:")
Console.WriteLine(ex.StackTrace)
Console.WriteLine()
PrintException(ex.InnerException)
}
}
private static void kNime_Bat(string ruta_del_archivoBat_knime)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo()
psi.UseShellExecute = false
psi.CreateNoWindow = true
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = ruta_del_archivoBat_knime
Process.Start(psi)
}
catch (Win32Exception)
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Start Watching"
t.Interval = 1000
t.Tick += new EventHandler(t_Tick)
}
private void t_Tick(object sender, EventArgs e)
{
if (togglelight)
{
button1.BackColor = Color.DarkBlue
togglelight = false
}
else
{
button1.BackColor = Color.Gray
togglelight = true
}
}
}
}
I have tried watcher.EnableRaisingEvents = false in Stopwatching event but it seems like if it works in a new instance as it does not stop the watcher, how I know? because after I click on "stop" I make a new change in the watched folder and I get an answer in OnChanged event.
I'm making an mp3 player in Xamarin.Forms, in which the slider should both show time expired and allow jumping to locations in the track.
As far as I can tell, only the ValueChanged event is available, with the unfortunate sideeffect that every time my timer updates the slider value, I also trigger my player.SeekTo method, causing broken playback.
Is there any way to specifically pick up touch events on a slider?
If not, does anyone have any suggestions on how to make this work?
In case it's relevant, here's my code for the MainPage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace MuZor
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
PlayButton.Clicked += PlayButton_Clicked;
PlaylistsButton.Clicked += PlaylistsButton_Clicked;
RandomButton.Clicked += RandomButton_Clicked;
RepeatButton.Clicked += RepeatButton_Clicked;
ChoiceButton.Clicked += ChoiceButton_Clicked;
PreviousButton.Clicked += PreviousButton_Clicked;
NextButton.Clicked += NextButton_Clicked;
TimeSlider.ValueChanged += TimeSlider_ValueChanged;
MessagingCenter.Subscribe<Interfaces.IAudioPlayer>(App.player, "PlayerPrepared", (args) =>
{
System.Diagnostics.Debug.WriteLine("Message received");
PlayerPrepared();
});
}
private void TimeSlider_ValueChanged(object sender, ValueChangedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Slider value changed, value = " + e.NewValue + "(int = " + (int)e.NewValue);
//App.player.SeekTo((int)e.NewValue);
}
private void NextButton_Clicked(object sender, EventArgs e)
{
if (!App.settings.RandomOn && App.settings.CurrentTrack < App.playlist.Count - 1)
{
Play((int)App.settings.CurrentTrack + 1);
}
}
private void PreviousButton_Clicked(object sender, EventArgs e)
{
if (!App.settings.RandomOn && App.settings.CurrentTrack > 0)
{
Play((int)App.settings.CurrentTrack - 1);
}
}
private void ChoiceButton_Clicked(object sender, EventArgs e)
{
}
private void RepeatButton_Clicked(object sender, EventArgs e)
{
}
private void RandomButton_Clicked(object sender, EventArgs e)
{
}
private void PlaylistsButton_Clicked(object sender, EventArgs e)
{
}
private void PlayButton_Clicked(object sender, EventArgs e)
{
if (App.settings.IsPaused || App.player.IsPlaying())
{
App.player.PauseResume();
if (App.settings.IsPaused)
{
UnPause();
}
else
{
Pause();
}
}
else
{
int trackToplay = App.settings.CurrentTrack != null ? (int)App.settings.CurrentTrack : 0;
Play(trackToplay);
}
}
private void Play(int currentTrack)
{
HelperClasses.SettingsHelper.SaveCurrentTrack(currentTrack);
App.player.LoadAndPlay(App.playlist[currentTrack].Path);
}
private void Pause()
{
HelperClasses.SettingsHelper.SavePausedState(true);
Device.BeginInvokeOnMainThread(() =>
{
PlayButton.Text = "Play";
});
}
private void UnPause()
{
HelperClasses.SettingsHelper.SavePausedState(false);
Device.BeginInvokeOnMainThread(() =>
{
PlayButton.Text = "Pause";
});
StartTimer();
}
private void StartTimer()
{
double position;
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
position = App.player.GetCurrentPosition();
TimeSpan runTime = TimeSpan.FromMilliseconds(position);
Device.BeginInvokeOnMainThread(() =>
{
TimeLabel.Text = runTime.ToString(#"mm\:ss");
TimeSlider.Value = position;
});
if (App.player.IsPlaying())
return true;
else
return false;
});
}
private void PlayerPrepared()
{
var totalDurationInMS = App.player.GetDuration();
TimeSlider.Maximum = totalDurationInMS;
TimeSlider.Minimum = 0;
TimeSpan totalDuration = TimeSpan.FromMilliseconds(totalDurationInMS);
Device.BeginInvokeOnMainThread(() =>
{
RemainingTimeLabel.Text = totalDuration.ToString(#"mm\:ss");
TimeLabel.Text = "00:00";
});
UnPause();
}
}
}
I think I've found a workaround. Since the valuechanged event contains both old and new values, I'll only fire SeekTo if the difference is negative or bigger than 2.
I have one Form which created as ascx control.Data was saving in biz form successfully. my problem is how to upload file? i dont know which control i'm using right or not for upload file? and how to add file upload submit here rec.SetValue("UploadCV", duUploadCV.InnerAttachmentGUID); you can see below click button code.i have both code ascx and .cs in below. my ascx upload control which i'm using is right or not ? design code is below. code .cs is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS.Base;
using CMS.DataEngine;
using CMS.DocumentEngine;
using CMS.EmailEngine;
using CMS.EventLog;
using CMS.FormControls;
using CMS.FormEngine;
using CMS.Helpers;
using CMS.Localization;
using CMS.MacroEngine;
using CMS.Membership;
using CMS.PortalControls;
using CMS.PortalEngine;
using CMS.Protection;
using CMS.SiteProvider;
using CMS.WebAnalytics;
using System.Data;
using CMS.GlobalHelper;
using CMS.TreeEngine;
using CMS.CMSHelper;
using CMS.SiteProvider;
using CMS.EmailEngine;
using CMS.EventLog;
using CMS.DataEngine;
using CMS.WebAnalytics;
using CMS.LicenseProvider;
using CMS.PortalEngine;
using CMS.SettingsProvider;
using CMS.IDataConnectionLibrary;
using CMS.OnlineForms;
using CMS.DataEngine;
using CMS.SiteProvider;
using CMS.Helpers;
using CMS.FormEngine;
using CMS.SettingsProvider;
using CMS.DataEngine;
using CMS.GlobalHelper;
using CMS.ExtendedControls;
using CMS.Helpers;
using CMS.UIControls;
using System.Text;
using System.Web.UI.WebControls;
public partial class CMSWebParts_ePortalWebPart_ePortalControl_GraduateProgramApplication : CMSAbstractWebPart
{
//public static int SaveSignupForm(SignupFormModel model)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetGender();
GetUniversity();
GetStudyArea();
GetSpecializationEng();
}
}
#region "Layout properties"
public override string SkinID
{
get
{
return base.SkinID;
}
set
{
base.SkinID = value;
SetSkinID(value);
}
}
public string NameText
{
get
{
return DataHelper.GetNotEmpty(GetValue("NameText"), ResHelper.LocalizeString("{$GPAName$}"));
}
set
{
SetValue("NameText", value);
lblName.Text = value;
}
}
#endregion
public string DOBText
{
get
{
return DataHelper.GetNotEmpty(GetValue("DOBText"), ResHelper.LocalizeString("{$GPADateOfBirth$}"));
}
set
{
this.SetValue("LastNameText", value);
lblDOB.Text = value;
}
}
public string EmailText
{
get
{
return DataHelper.GetNotEmpty(this.GetValue("EmailText"), ResHelper.LocalizeString("{$Webparts_Membership_RegistrationForm.Email$}"));
}
set
{
this.SetValue("EmailText", value);
lblEmail.Text = value;
}
}
public string Submit
{
get
{
return DataHelper.GetNotEmpty(GetValue("Submit"), ResHelper.LocalizeString("{$custom.custom.Submit$}"));
}
set
{
this.SetValue("Submit", value);
btnOk.Text = value;
}
}
public string Gender
{
get
{
return DataHelper.GetNotEmpty(GetValue("Gender"), ResHelper.LocalizeString("{$GPAGender$}"));
}
set
{
this.SetValue("Gender", value);
lblGender.Text = value;
}
}
public string Email
{
get
{
return DataHelper.GetNotEmpty(GetValue("Email"), ResHelper.LocalizeString("{$GPAEmail$}"));
}
set
{
this.SetValue("Email", value);
lblEmail.Text = value;
}
}
public string GSMNumber
{
get
{
return DataHelper.GetNotEmpty(GetValue("GSMNumber"), ResHelper.LocalizeString("{$GPAGSMNumber$}"));
}
set
{
this.SetValue("GSMNumber", value);
lblGSMNumber.Text = value;
}
}
public string Grade
{
get
{
return DataHelper.GetNotEmpty(GetValue("Grade"), ResHelper.LocalizeString("{$GPAGrade$}"));
}
set
{
this.SetValue("Grade", value);
lblGrade.Text = value;
}
}
public string ExpectGraduateDate
{
get
{
return DataHelper.GetNotEmpty(GetValue("ExpectGraduateDate"), ResHelper.LocalizeString("{$GPAExpectGraduateDate$}"));
}
set
{
this.SetValue("ExpectGraduateDate", value);
lblExpectGraduateDate.Text = value;
}
}
public string University
{
get
{
return DataHelper.GetNotEmpty(GetValue("University"), ResHelper.LocalizeString("{$GPAUniversity$}"));
}
set
{
this.SetValue("University", value);
lblUniversity.Text = value;
}
}
public string StudyArea
{
get
{
return DataHelper.GetNotEmpty(GetValue("StudyArea"), ResHelper.LocalizeString("{$GPAStudyArea$}"));
}
set
{
this.SetValue("StudyArea", value);
lblStudyArea.Text = value;
}
}
public string Specialization
{
get
{
return DataHelper.GetNotEmpty(GetValue("Specialization"), ResHelper.LocalizeString("{$GPASpecialization$}"));
}
set
{
this.SetValue("Specialization", value);
lblSpecialization.Text = value;
}
}
public string WhyJoinPAEW
{
get
{
return DataHelper.GetNotEmpty(GetValue("WhyJoinPAEW"), ResHelper.LocalizeString("{$GPAWhyJoinPAEW$}"));
}
set
{
this.SetValue("WhyJoinPAEW", value);
lblWhyJoinPAEW.Text = value;
}
}
public string UploadCV
{
get
{
return DataHelper.GetNotEmpty(GetValue("UploadCV"), ResHelper.LocalizeString("{$GPAUploadCV$}"));
}
set
{
this.SetValue("UploadCV", value);
lblUploadCV.Text = value;
}
}
public string Certificates
{
get
{
return DataHelper.GetNotEmpty(GetValue("Certificates"), ResHelper.LocalizeString("{$GPACertificates$}"));
}
set
{
this.SetValue("Certificates", value);
lblCertificates.Text = value;
}
}
protected void SetupControl()
{
if (this.StopProcessing)
{
// Do not process
rfvName.Enabled = false;
rfvDOB.Enabled = false;
rfvEmail.Enabled = false;
revEmail.Enabled = false;
rfvGSMNumber.Enabled = false;
revMobile.Enabled = false;
rvGrade.Enabled = false;
rfvGrade.Enabled = false;
rvExpectGraduateDate.Enabled = false;
rfvExpectGraduateDate.Enabled = false;
rfvUniversity.Enabled = false;
rfvWhyJoinPAEW.Enabled = false;
// rfvUploadCV.Enabled = false;
// rfvCertificates.Enabled = false;
}
else
{
// Set texts
lblName.Text = this.NameText;
lblDOB.Text = this.DOBText;
btnOk.Text = this.Submit;
lblGender.Text = this.Gender;
lblEmail.Text = this.Email;
lblGSMNumber.Text = this.GSMNumber;
lblGrade.Text = this.Grade;
lblExpectGraduateDate.Text = this.ExpectGraduateDate;
lblUniversity.Text = this.University;
lblStudyArea.Text = this.StudyArea;
lblSpecialization.Text = this.Specialization;
lblWhyJoinPAEW.Text = this.WhyJoinPAEW;
lblUploadCV.Text = this.UploadCV;
lblCertificates.Text = this.Certificates;
//lddSpecialization.Items.Insert(0, new ListItem(ResHelper.GetString(ResHelper.LocalizeString("{$GPASpecialization$}"),CultureHelper.GetPreferredCulture())));
// BizForm1.OnAfterSave += new BizForm.OnAfterSaveEventHandler(GetGender());
// ObjectEvents.Insert.After += new EventHandler<ObjectEventArgs>(Insert_After);
// Set required field validators texts
rfvName.ErrorMessage = ResHelper.GetString("GPArfv");
rfvDOB.ErrorMessage = ResHelper.GetString("GPArfv");
rfvEmail.ErrorMessage = ResHelper.GetString("GPArfv");
revEmail.ErrorMessage = ResHelper.GetString("GPArfv");
rfvGSMNumber.ErrorMessage = ResHelper.GetString("GPArfv");
revMobile.ErrorMessage = ResHelper.GetString("GPArevMobile");
rvGrade.ErrorMessage = ResHelper.GetString("GPAGradeLess");
rfvGrade.ErrorMessage = ResHelper.GetString("GPArfv");
rvExpectGraduateDate.ErrorMessage = ResHelper.GetString("GPArvExpectGraduateDate");
rfvExpectGraduateDate.ErrorMessage = ResHelper.GetString("GPArfv");
rfvUniversity.ErrorMessage = ResHelper.GetString("GPArfv");
rfvWhyJoinPAEW.ErrorMessage = ResHelper.GetString("GPArfv");
// rfvUploadCV.ErrorMessage = ResHelper.GetString("Webparts_Membership_RegistrationForm.rfvLastName");
// rfvCertificates.ErrorMessage = ResHelper.GetString("Webparts_Membership_RegistrationForm.rfvLastName");
// Set SkinID
if (!this.StandAlone && (this.PageCycle < PageCycleEnum.Initialized))
{
SetSkinID(this.SkinID);
}
}
}
void SetSkinID(string skinId)
{
if (skinId != "")
{
lblName.SkinID = skinId;
lblDOB.SkinID = skinId;
}
}
public override void OnContentLoaded()
{
base.OnContentLoaded();
SetupControl();
}
/// <summary>
/// Reloads data
/// </summary>
public override void ReloadData()
{
base.ReloadData();
SetupControl();
}
/////////////////// Append Gender Radio List ///////////////////
private void GetGender()
{
Dictionary<string, string> Genderdic = new Dictionary<string, string>();
Genderdic.Add("1", "Male"); Genderdic.Add("2", "Female");
rvGender.DataSource = Genderdic;
rvGender.DataValueField = "Key";
rvGender.DataTextField = "Value";
rvGender.DataBind();
rvGender.SelectedValue = "1";
}
/////////////////// Append Gender Radio List ///////////////////
private void GetUniversity()
{
Dictionary<string, string> Universitydic = new Dictionary<string, string>();
Universitydic.Add("1", "Sultan Qaboos University"); Universitydic.Add("2", "Higher College of Technology"); Universitydic.Add("3", "Other");
ddlUniversity.DataSource = Universitydic;
ddlUniversity.DataValueField = "Key";
ddlUniversity.DataTextField = "Value";
ddlUniversity.DataBind();
}
private void GetStudyArea()
{
Dictionary<string, string> StudyAreadic = new Dictionary<string, string>();
StudyAreadic.Add("1", "Engineering"); StudyAreadic.Add("2", "Business");
rblStudyArea.DataSource = StudyAreadic;
rblStudyArea.DataValueField = "Key";
rblStudyArea.DataTextField = "Value";
rblStudyArea.DataBind();
rblStudyArea.SelectedValue = "1";
}
private void GetSpecializationEng()
{
Dictionary<string, string> Specializationdic = new Dictionary<string, string>();
if (rblStudyArea.SelectedValue == "1")
{
Specializationdic.Add("1", "Mechanical"); Specializationdic.Add("2", "Instrumentation"); Specializationdic.Add("3", "Civil"); Specializationdic.Add("4", "Chemistry"); Specializationdic.Add("5", "Water Resources"); Specializationdic.Add("6", "Other");
}
else
{
Specializationdic.Add("1", "Finance"); Specializationdic.Add("2", "HR"); Specializationdic.Add("3", "Communication"); Specializationdic.Add("4", "BA"); Specializationdic.Add("5", "Other");
}
lddSpecialization.DataSource = Specializationdic;
lddSpecialization.DataValueField = "Key";
lddSpecialization.DataTextField = "Value";
lddSpecialization.DataBind();
lddSpecialization.SelectedValue = "1";
}
protected void ddlUniversity_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlUniversity.SelectedValue == "3")
{ txtUniversity.Visible = true;}
else
{ txtUniversity.Visible = false;}
}
protected void rblStudyArea_SelectedIndexChanged(object sender, EventArgs e)
{
GetSpecializationEng();
}
protected void lddSpecialization_SelectedIndexChanged(object sender, EventArgs e)
{
if (rblStudyArea.SelectedValue == "1")
{
if (lddSpecialization.SelectedValue == "6")
{ txtSpecialization.Visible = true; }
else
{ txtSpecialization.Visible = false; }
}
else
{
if (lddSpecialization.SelectedValue == "5")
{ txtSpecialization.Visible = true; }
else
{ txtSpecialization.Visible = false; }
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible))
{
// Do not process
}
else
{
rfvName.Validate();
rfvDOB.Validate();
rfvEmail.Validate();
revEmail.Validate();
rfvGSMNumber.Validate();
revMobile.Validate();
rvGrade.Validate();
rfvGrade.Validate();
rvExpectGraduateDate.Validate();
rfvExpectGraduateDate.Validate();
rfvUniversity.Validate();
rfvWhyJoinPAEW.Validate();
Page.Validate();
//if (Page.IsValid)
//{
String siteName = SiteContext.CurrentSiteName;
#region "Banned IPs"
// Ban IP addresses which are blocked for registration
if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
{
lblError.Visible = true;
lblError.Text = GetString("banip.ipisbannedregistration");
return;
}
#endregion
BizFormInfo formObject = BizFormInfoProvider.GetBizFormInfo("GraduateProgramApplication", SiteContext.CurrentSiteID);
if (formObject != null)
{
DataClassInfo formClass = DataClassInfoProvider.GetDataClassInfo(formObject.FormClassID);
if (formClass != null)
{
BizFormItemProvider bProvider = new BizFormItemProvider();
BizFormItem rec = BizFormItem.New(formClass.ClassName, null);
DateTime Applicant_DOB = DateTime.ParseExact(txtDOB.Text.Trim(), "dd/MM/yyyy", null);
DateTime Applicant_ExpectGraduateDate = DateTime.ParseExact(txtExpectGraduateDate.Text.Trim(), "MM/dd/yyyy", null);
rec.SetValue("FullName", txtName.Text.Trim());
rec.SetValue("DOB", Applicant_DOB);
rec.SetValue("Gender", rvGender.SelectedItem.Text.Trim());
rec.SetValue("Email", txtEmail.Text.Trim());
rec.SetValue("GSMNumber", txtGSMNumber.Text.Trim());
rec.SetValue("Grade", txtGrade.Text.Trim());
rec.SetValue("ExpectGraduateDate", Applicant_ExpectGraduateDate);
rec.SetValue("University", ddlUniversity.SelectedItem.Text.Trim());
rec.SetValue("StudyArea", rblStudyArea.SelectedItem.Text.Trim());
rec.SetValue("Specialization", lddSpecialization.SelectedItem.Text.Trim());
rec.SetValue("WhyPAEW", txtWhyJoinPAEW.Text.Trim());
// rec.SetValue("UploadCV", duUploadCV.InnerAttachmentGUID);
// BasicForm.Data.GetValue("answerText"), "");
rec.SetValue("FormInserted", DateTime.Now);
rec.SetValue("FormUpdated", DateTime.Now);
rec.Insert();
BizFormInfoProvider.RefreshDataCount(formObject.FormName, formObject.FormSiteID);
}
}
string test = "Hello";
Response.Write("<script>alert('" + test + "');</script>");
}
}
}
I think you'll need to trigger the direct uploader to save the file somehow, before it will give you a GUID - I'm not completely familiar with how it works because I've never used it outside of the context of the Kentico form engine.
That being said, I think that the Forms module in Kentico would do everything that I can see you're trying to do here without you needing to write custom code.
Whenever I create a form in Kentico I try to leverage the forms module as much as possible.
I would recommend reading through the documentation for the forms module for whichever version of Kentico you're using to try create the form through the User Interface, and then asking questions if you get stuck on something through that process - unless there's something custom that I've misunderstood.
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);
}
}
}
I'm building a library of custom controls. My controls are inherited from CompositeControl.
Depending on the user's answer I have to insert more custom control. I have a PlaceHolder (_ph) passed in from the client code. I insert my controls into that PlaceHolder.
My problem is the control I inserted in the event handler does not fire its event, but it fires the parent event. For example, if I have an EddDropDown A, and the user picks an answer, I have to create EddDropDown B and C in edd_SelectedIndexChanged. When I pick an answer for B, it fires SelectedIndexChanged for A instead of B.
I think it has something to do with entering the page cycle late. I don't know how to fix it. Please help. Really appreciate any assistant.
Thanks in advance.
this is an example of my controls:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommerceBank.DueDiligence.ServiceProxies.Internal.Edd;
using System.Collections.Specialized;
using System.Runtime.Serialization;
namespace CommerceBank.DueDiligence.ClientFacade.WebForms
{
public class EddDropDownListArgs : EventArgs
{
private int _iQuestionID;
string _sAnswer = string.Empty;
private DueDiligenceProfile _customerProfile;
public EddDropDownListArgs(int iQuestionID, string sAnswer,DueDiligenceProfile customer)
{
_iQuestionID = iQuestionID;
_sAnswer = sAnswer;
_customerProfile = customer;
}
public int QuestionID
{
get
{
return _iQuestionID;
}
set
{
_iQuestionID = value;
}
}
public string Answer
{
get
{
return _sAnswer;
}
set
{
_sAnswer = value;
}
}
public DueDiligenceProfile customerProfile
{
get
{
return _customerProfile;
}
set
{
_customerProfile = value;
}
}
}
public delegate void EddDropDownSelectedIndexChangedHandler(object sender, EddDropDownListArgs ce);
[
AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
DefaultProperty("ID"),
ToolboxData("<{0}:EddDropDown runat=\"server\"> </{0}:EddDropDown>"),
Serializable
]
public class EddDropDown : CompositeControl, IChannelControl,ISerializable, IPostBackEventHandler, IPostBackDataHandler
{
[Serializable]
struct EddDropDownData
{
public int _iQuestionID;
public String _sQuestion;
//public AnswerOption[] _PossibleAnswers;
public String _sAnswer;
//public DueDiligenceProfile _customerProfile;
}
[
Bindable(true),
Category("Appearance"),
DefaultValue(""),
Description("This is EddCheckBox"),
Localizable(true)
]
private int _iQuestionID=-1;
private String _sQuestion = string.Empty;
private AnswerOption[] _PossibleAnswers;
private String _sAnswer = string.Empty;
private DueDiligenceProfile _customerProfile;
private EddDropDownData _data = new EddDropDownData();
Label _lQuestion = null;
DropDownList _ddl = null;
#region implement custom events
public event EddDropDownSelectedIndexChangedHandler SelectedIndexChanged;
protected virtual void OnSelectedIndexChanged(EddDropDownListArgs eddEvent)
{
if (SelectedIndexChanged != null)
{
System.Diagnostics.Trace.WriteLine("OnSelectedIndexChanged. QuestionID:"
+ eddEvent.QuestionID
+ " Answer: "
+ eddEvent.Answer);
SelectedIndexChanged(this, eddEvent);
}
}
#endregion
#region IPostBackEventHandler_implementation
// Define the method of IPostBackEventHandler that raises change events.
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
System.Diagnostics.Trace.WriteLine("in RaisePostBackEvent" + eventArgument);
OnSelectedIndexChanged(new EddDropDownListArgs(EDDQuestionID(), EDDAnswerValue(), _customerProfile));
}
#endregion
#region IPostBackDataHandler_implementation
bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
{
//System.Diagnostics.Trace.WriteLine("in LoadPostData");
//int i = int.Parse(postCollection["SelectedIndex"]);
//string s = postCollection["SelectedValue"];
//if (SelectedIndex >= 0)
// Page.RegisterRequiresRaiseEvent(this);
//return false;
return true;
}
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
System.Diagnostics.Trace.WriteLine("in RaisePostDataChangedEvent");
}
#endregion
#region ISerializable_implementation
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ControlType", GetType().Name);
info.AddValue("ControlID", ID);
info.AddValue("QuestionID", _iQuestionID);
info.AddValue("Question", Question);
info.AddValue("Answer", EDDAnswerValue());
info.AddValue("PossibleAnswerCount", _PossibleAnswers.Length);
for (int i=0; i < _PossibleAnswers.Length; i++)
{
info.AddValue("a" + i.ToString(), _PossibleAnswers[i]);
}
}
#endregion
#region IChannel_implementation
public int EDDQuestionID()
{
return QuestionID;
}
public string EDDAnswerValue()
{
EnsureChildControls();
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i].ID == "ans" + QuestionID)
{
_sAnswer = ((DropDownList)Controls[i]).SelectedValue;
_data._sAnswer = ((DropDownList)Controls[i]).SelectedValue;
ViewState["SelectedIndex"] = ((DropDownList)Controls[i]).SelectedIndex;
return ((DropDownList)Controls[i]).SelectedValue;
}
}
return null;
}
#endregion
#region Overriden properties
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
#endregion
#region Properties
public int QuestionID
{
get
{
_iQuestionID = (int)ViewState["QuestionID"];
return _iQuestionID;
}
set
{
ViewState["QuestionID"] = value;
_iQuestionID = value;
}
}
public string Question
{
get
{
_sQuestion = (string)ViewState["Question"];
return _sQuestion;
}
set
{
ViewState["Question"] = value;
_sQuestion = value;
}
}
public string Answer
{
get
{
return _sAnswer;
}
set
{
_sAnswer = value;
}
}
public int SelectedIndex
{
get {
EnsureChildControls();
if (ViewState["SelectedIndex"] != null)
_ddl.SelectedIndex = (int)ViewState["SelectedIndex"];
else
_ddl.SelectedIndex = 0;
return _ddl.SelectedIndex;
}
set {
EnsureChildControls();
ViewState["SelectedIndex"] = value;
_ddl.SelectedIndex = value;
}
}
public string SelectedValue
{
get
{
EnsureChildControls();
_ddl.SelectedValue =(string)ViewState["SelectedValue"];
return _ddl.SelectedValue;
}
set
{
EnsureChildControls();
ViewState["SelectedValue"] = value;
_ddl.SelectedValue = value;
}
}
#endregion
public EddDropDown(int iQuestionID
, string sQuestion
, DueDiligenceProfile cust
, AnswerOption[] sPossibleAnswers
)
{
System.Diagnostics.Trace.WriteLine("Add EddDropDown. QuestionID :"
+ iQuestionID.ToString()
+ sQuestion);
QuestionID = iQuestionID;
Question = sQuestion;
_data._iQuestionID = iQuestionID;
_data._sQuestion = sQuestion;
_PossibleAnswers = sPossibleAnswers;
_customerProfile = cust;
ID = iQuestionID.ToString()+GetCustomerID();
}
public EddDropDown(SerializationInfo info, StreamingContext context)
{
string sControlType = info.GetString("ControlType");
ID = info.GetString("ControlID");
QuestionID = info.GetInt32("QuestionID");
Question = info.GetString("Question");
string sAnswer = info.GetString("Answer");
int iAnswerCount = info.GetInt32("PossibleAnswerCount");
List<AnswerOption> answerOptions = new List<AnswerOption>();
for (int i = 0; i < iAnswerCount; i++)
{
Type t = typeof(AnswerOption);
AnswerOption ao = (AnswerOption)info.GetValue("a" + i.ToString(), t);
answerOptions.Add(ao);
}
_PossibleAnswers = answerOptions.ToArray();
}
protected override object SaveViewState()
{
ViewState["SelectedIndex"] = _ddl.SelectedIndex;
return base.SaveViewState();
}
protected override void LoadViewState(object savedState)
{
//if (ViewState["SelectedIndex"] != null)
// _ddl.SelectedIndex = (int)ViewState["SelectedIndex"];
//else
// _ddl.SelectedIndex = 0;
if (savedState != null)
{
Pair mystate = (Pair)savedState;
ArrayList al =(ArrayList)mystate.First;
for (int i = 0; i < al.Count;i++ )
{
if (al[i].GetType().Name == "IndexedString")
{
if (((IndexedString)al[i]).Value == "SelectedIndex")
{
ViewState["SelectedIndex"] = al[i + 1].ToString();
System.Diagnostics.Trace.WriteLine(al[i + 1].ToString());
}
}
}
}
base.LoadViewState(savedState);
}
//need this to get the post back
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ID);
writer.AddAttribute(HtmlTextWriterAttribute.Onchange,
Page.ClientScript.GetPostBackEventReference(this, ID));
//writer.AddAttribute(HtmlTextWriterAttribute.Onchange,
// Page.ClientScript.GetPostBackEventReference(_ddl, _ddl.ID));
base.AddAttributesToRender(writer);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
Page.RegisterRequiresPostBack(this);//must register postback in OnPreRender
}
protected override void Render(HtmlTextWriter writer)
{
//Ensures that this control is nested in a server form
if (Page != null)
{
Page.VerifyRenderingInServerForm(this);
}
base.Render(writer);
}
protected override void RenderContents(HtmlTextWriter writer)
{
RenderChildren(writer);
}
protected override void CreateChildControls()
{
Controls.Clear();
_lQuestion = new Label();
_lQuestion.ID = "quest" + QuestionID;
_lQuestion.Text = Question;
_ddl = new DropDownList();
_ddl.ID = "ans" + QuestionID;
//add "select one"
ListItem liSelectOne = new ListItem("Please select one");
_ddl.Items.Add(liSelectOne);
for (int i = 0; i < _PossibleAnswers.Count(); i++)
{
AnswerOption a = _PossibleAnswers[i];
ListItem li = new ListItem(a.Value.ToString());
_ddl.Items.Add(li);
//if (a.ChildQuestions == null)//default it to the answer that don't have some children
// ddl.Items[i].Selected = true;
}
if (_sAnswer != string.Empty)
_ddl.SelectedValue = _sAnswer;
_ddl.AutoPostBack = true;//must have
_ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
if (ViewState["SelectedIndex"] != null)
_ddl.SelectedIndex = (int)ViewState["SelectedIndex"];
//else
// _ddl.SelectedIndex = 0;
Page.RegisterRequiresPostBack(_ddl);
Page.RegisterRequiresControlState(_ddl);
Controls.Add(new LiteralControl("<br>"));
Controls.Add(_lQuestion);
Controls.Add(new LiteralControl("<br>"));
Controls.Add(_ddl);
ChildControlsCreated = true;
//ClearChildViewState();
}
private string GetCustomerID()
{
if (_customerProfile.Customer.PermanentId >0)
return _customerProfile.Customer.PermanentId.ToString();
else if (_customerProfile.Customer.RcifId != null && _customerProfile.Customer.RcifId != "")
return _customerProfile.Customer.RcifId;
else
return _customerProfile.Customer.TaxId.ToString();
}
//to do: delete
//void edd_SelectedIndexChanged(object sender, EddDropDownListArgs ea)
//{
// System.Diagnostics.Trace.WriteLine("get here");
//}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Control c = (Control)sender;
System.Diagnostics.Trace.WriteLine("ddl_SelectedIndexChanged "
+ c.GetType().Name);
OnSelectedIndexChanged(new EddDropDownListArgs(EDDQuestionID(), EDDAnswerValue(),_customerProfile));
}
protected override void RenderChildren(HtmlTextWriter output)
{
if (HasControls())
{
for (int i = 0; i < Controls.Count; i++)
{
Controls[i].RenderControl(output);
}
}
}
}
}
This is the code that create the controls:
public EddDropDown GetDropDown(DueDiligenceProfile cust, Question quest)
{
Control c = null;
if (HasControl(quest.Id.ToString(), "EddDropDown", ref c))
return (EddDropDown)c;
string sQuestion = null;
AnswerOption[] sPossAnswers;
sPossAnswers = FindPossibleAnswers(cust.Questions, quest.Id, ref sQuestion);
if (sPossAnswers == null)
throw (new Exception("failed to get possible answers"));
EddDropDown edd = new EddDropDown(quest.Id,
sQuestion,
cust,
sPossAnswers
);
edd.ID = quest.Id.ToString();
edd.SelectedIndexChanged += new EddDropDownSelectedIndexChangedHandler(edd_SelectedIndexChanged);
_data._EDDControls.Add(edd);
int iParentQuestionID = FindParentQuestionID(cust.Questions, quest.Id, ref sQuestion);
int iControlIdx = GetIndexOf(iParentQuestionID, _ph.Controls);
if (iControlIdx >-1)
_ph.Controls.AddAt(iControlIdx + 1, edd);
else
_ph.Controls.Add(edd);
//build children questions if they have result
if (quest.Results.Length >0)
{
foreach (Result r in quest.Results)
{
edd.SelectedValue = r.Value;
foreach (AnswerOption ao in quest.AnswerOptions)
{
if (r.Value == ao.Value)
{
if (ao.ChildQuestions == null)
continue;
foreach (Question q in ao.ChildQuestions)
{
EddDropDown e = GetDropDown(cust, q);
e.BackColor = System.Drawing.Color.CadetBlue;
}
}
}
}
}
return edd;
}
void edd_SelectedIndexChanged(object sender, EddDropDownListArgs ea)
{
System.Diagnostics.Trace.WriteLine("EddQuestionare--edd_SelectedIndexChanged. QuestionID:"
+ ea.QuestionID
+ " Answer: "
+ ea.Answer);
//Control parentControl = null;
//if (sender.GetType().Name == "EddDropDown")
//{
// parentControl = (Control)sender;
//}
//Control c = (Control)sender;
//while (c.GetType().Name != "PlaceHolder")
// c = c.Parent;
string sQuestion = null;
AnswerOption[] ansOptions = FindPossibleAnswers(ea.customerProfile.Questions
, ea.QuestionID
, ref sQuestion);
foreach (AnswerOption ao in ansOptions)
{
if (ao.Value == ea.Answer)//found answer
{
if (ao.ChildQuestions == null)
break;
//create sub questions
for (int i = 0; i < ao.ChildQuestions.Length; i++)//and there are subquestions
{
_ph.Controls.Add(new LiteralControl(" "));
if (ao.ChildQuestions[i].AnswerOptions.Length > 2)
{
EddDropDown subQues = GetDropDown(ea.customerProfile
, ao.ChildQuestions[i]);
subQues.BackColor = System.Drawing.Color.Aqua;
}
else if (ao.ChildQuestions[i].AnswerOptions.Length == 2)
{
EddRadioButtonList erb = GetRadioButtonList(ea.customerProfile
, ao.ChildQuestions[i].Id);
erb.BackColor = System.Drawing.Color.BlueViolet;
}
else
{
EddTextArea eta = GetTextArea(ea.customerProfile
, ao.ChildQuestions[i].Id);
eta.BackColor = System.Drawing.Color.Bisque;
}
}
break;
}
}
//DisplayControls();
//Serialize();
}
There are a few things that I haven't cleaned out, but you get the idea.
The postback events might not be getting to your control.
In the page that is using your controls, try overriding the RaisePostbackEvent and call the RaisePostBackEvents for each control:
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
this.yourcustomcontrol1.RaisePostBackEvent(sourceControl, eventArgument);
this.yourcustomcontrol2.RaisePostBackEvent(sourceControl, eventArgument);
base.RaisePostBackEvent(sourceControl, eventArgument);
}