Force String.Format "{0:P4}" to show + sign - devexpress

I have a decimal column in my Database where values are stored as 12.35
We show it as 12.35%
The client wants to show +12.35% if the value is positive(just for this one field). How I do get it to show the +sign.
We format the textedit as P4 in the getter String.Format("{0:P4}", value);
This is what I've tried:
I was able to do this by using Fomrat event handler. I am looking for a cleaner way instead of the below code.
private void txtMargin_FormatEditValue(object sender, DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs e)
{
if (e.Value != null)
{
if (e.Value.ToString().IndexOfAny(new char[] { '-', '+' }) < 0)
{
string val = e.Value.ToString();
val = val.Replace("%", "");
e.Value = string.Format("+{0}", (Convert.ToDouble(val) / 100).ToString("P4"));
e.Handled = true;
}
else
{
string val = e.Value.ToString();
val = val.Replace("%", "");
e.Value = (Convert.ToDouble(val) / 100).ToString("P4");
}
e.Handled = true;
}
}
private void txtMargin_ParseEditValue(object sender, DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs e)
{
if (e.Value != null)
{
if (e.Value.ToString().IndexOf('%') < 0)
{
e.Value = (Convert.ToDouble(e.Value.ToString()) / 100).ToString("P4");
}
}
}

In your form load past this code :
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textEdit1.Properties.Mask.EditMask = "+#0.0000% ;-#0.0000%";
textEdit1.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
textEdit1.Properties.Mask.UseMaskAsDisplayFormat = false;
textEdit1.Properties.EditFormat.FormatString = "+#0.0000% ;-#0.0000%";;
}
And in you TextBox Handel the event "`CustomDisplayText`" as :
private void textEdit1_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
{
if (e.Value != null && !e.Value.Equals (""))
e.DisplayText = (Convert.ToDouble(e.Value.ToString()) / 100).ToString("+#0.0000 % ;-#0.0000 %");
}

Related

how to stop my FileSystemWatcher in start/stop button

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.

check if button is clicked in if() condition aspx.net

I want to check if btnTest_Click is clicked in another Button6_Click event.Below is my code.....Please help
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if()
}
as per Kevin's answer but instead of:
protected bool testPassed;
Have this:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
By accessing the value of this property via view state the value will persist between requests.
I would declare a class level boolean called testPassed.
Set it to false in the onload event if it is not a Postback.
Set it to true in the btnTest_Click event handler
Edit to add an example:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
testPassed=false;
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
testPassed=true;
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if(testPassed)
}

UserAccounts_RowEditing/Updating is not working properly

Alright, so I have a Gridview and added RowEditing and RowUpdating to it, but it won't really edit something.. This is my code for both:
protected void UserAccounts_RowEditing(object sender, GridViewEditEventArgs e)
{
UserAccounts.EditIndex = e.NewEditIndex;
BindUserAccounts();
}
protected void UserAccounts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = UserAccounts.EditIndex;
GridViewRow row = UserAccounts.Rows[e.RowIndex];
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
email = ((TextBox)row.Cells[2].Controls[0]).Text;
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
user.Email = email;
Membership.UpdateUser(user);
ActionStatus.Text = string.Format("User {0} details have been successfully updated!", username);
}
UserAccounts.EditIndex = -1;
BindUserAccounts();
}
What am I doing wrong in here?
EDIT: This is my BindUserAccounts:
private void BindUserAccounts()
{
int totalRecords;
UserAccounts.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
UserAccounts.DataBind();
bool visitingFirstPage = (this.PageIndex == 0);
lnkFirst.Enabled = !visitingFirstPage;
lnkPrev.Enabled = !visitingFirstPage;
int lastPageIndex = (totalRecords - 1) / this.PageSize;
bool visitingLastPage = (this.PageIndex >= lastPageIndex);
lnkNext.Enabled = !visitingLastPage;
lnkLast.Enabled = !visitingLastPage;
}
i think the should be like this
protected void update_click_foredu(object sender, GridViewUpdateEventArgs e)
{
Label edui = (Label)edugrid.Rows[e.RowIndex].FindControl("label");
TextBox unitxt = (TextBox)edugrid.Rows[e.RowIndex].FindControl("txtuni");
if (unitxt != null && costxt != null && startdatetxt != null && enddatetxt != null)
{
using (Entities1 context = new Entities1())
{
string eduID = edui.Text;
model obj = context.entitytabel.First(x => x.ID == eduID);
obj.Univ_Name = unitxt.Text;
context.SaveChanges();
lblMessage.Text = "Saved successfully.";
edugrid.EditIndex = -1;
bindgrid();
}
}
}
here im using EF like this you can find the control of the text box and save it in gridview
hope this helps you
Somehow it works now after editing the GridView and set "UserName", "IsApproved", "IsLockedOut" and "IsOnline" to ReadOnly="true"

Is this the best/correct way to use the DevExpress ASPxGridView to edit a List<T>?

Would someone who knows DeveExpess ASPxGridView take a look at this.
Is this the best/correct way to use the grid to edit a List?
I have an object of Type ItemModel and the code below is used to allow an ASP.NET Web Site user to do CRUD operations on list of ItemModels.
My problem is that it seems too complex and I suspect I am not taking good advantage of the Grid.
For simplicity, I have left the Database Access Code that will load and save the list of ItemModels.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
BindGrid();
}
protected void OnRowInserting(object sender, ASPxDataInsertingEventArgs e)
{
IList<ItemModel> itemModels = CachedModels;
int lineID = 0;
if (itemModels .Count > 0)
{
lineID = itemModels[itemModels.Count - 1].LineID + 1;
}
ItemModel itemModel = new ItemModel()
{
, Code = e.NewValues["Code"] == null ? string.Empty : e.NewValues["Code"].ToString()
, Name = e.NewValues["Name"] == null ? string.Empty : e.NewValues["Name"].ToString()
, DateCreated = DateTime.Now
, DateUpdated = DateTime.Now
};
itemModels.Add(itemModel);
CachedModels = itemModels;
ASPxGridView aspxGridView = (ASPxGridView)sender;
aspxGridView.CancelEdit();
e.Cancel = true;
BindGrid();
}
protected void OnRowUpdating(object sender, ASPxDataUpdatingEventArgs e)
{
IList<ItemModel> itemModels = CachedModels;
int lineID = Convert.ToInt32(e.Keys[0].ToString());
ItemModel itemModel = null;
foreach (ItemModel model in itemModels)
{
if (model.LineID == lineID)
{
itemModel = model;
break;
}
}
if (itemModel != null)
{
itemModel.Code = e.NewValues["Code"] == null ? string.Empty : e.NewValues["Code"].ToString();
itemModel.Name = e.NewValues["Name"] == null ? string.Empty : e.NewValues["Name"].ToString();
containerItemModel.DateUpdated = DateTime.Now;
itemModels[lineID] = itemModel;
CachedModels = itemModels;
}
ASPxGridView aspxGridView = (ASPxGridView)sender;
aspxGridView.CancelEdit();
e.Cancel = true;
BindGrid();
}
protected void OnRowDeleting(object sender, ASPxDataDeletingEventArgs e)
{
IList<ItemModel> itemModels = CachedModels;
int lineID = Convert.ToInt32(e.Keys[0].ToString());
ItemModel itemModel = null;
foreach (ItemModel model in itemModels)
{
if (model.LineID == lineID)
{
itemModel = model;
break;
}
}
if (itemModel != null)
{
itemModels.Remove(itemModel);
CachedModels = itemModels;
}
ASPxGridView aspxGridView = (ASPxGridView)sender;
aspxGridView.CancelEdit();
e.Cancel = true;
BindGrid();
}
private void BindGrid()
{
grdItems.DataSource = CachedModels;
grdItems.DataBind();
}
private IList<ItemModel> CachedModels
{
get
{
List<ItemModel> models= (List<ItemModel>)Session["ItemModels"];
if (models == null)
{
models= new List<ItemModel>();
Session["ItemModels"] = models;
}
return models;
}
set
{
Session["ItemModels"] = value;
}
}
I believe your current code is quite correct.
Here is the suggested way from DX:
ASPxGridView - How to implement CRUD operations with a custom data source

ASP custom controls don't fire correct events

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);
}

Resources