IsHandleCreated Prop. is always false for gridview control in dev express - devexpress

My windows form contains ​DevExpress.XtraGrid.GridControl on Form1 similar way there is also 2nd class called it as Form2. On Form1 I am loading data from database. When I double click on grid row it assigns to an Form2. on Form1 gridControl1_DoubleClick event IsHandleCreated prop is true (Form2 is Inherited from Form1)
void gridControl1_DoubleClick(object sender, EventArgs e)
{
if (gridControl1.IsHandleCreated)
{
}
Form2 obj = new Form2();
obj.Display();
}
so I have created one property like on Form1
public GridControl GridControl1
{
get { return gridControl1; }
}
but when I call the Display() method of Form2 and check the IsHandleCreated prop on Form2 is false.
public void Display()
{
if (handleCreated)
{
}
}
complete code as below **Form1**
public partial class Form1 : Form
{
public GridControl GridControl1
{
get { return gridControl1; }
}
public bool handleCreated
{
get { return gridControl1.IsHandleCreated; }
}
public Form1()
{
InitializeComponent();
gridControl1.DataSource = CreateTable(20);
gridControl1.DoubleClick += gridControl1_DoubleClick;
}
void gridControl1_DoubleClick(object sender, EventArgs e)
{
if (gridControl1.IsHandleCreated)
{
}
Form2 obj = new Form2();
obj.Display();
}
private DataTable CreateTable(int rowCount)
{
DataTable table = new DataTable();
table.Columns.Add("String", typeof(string));
table.Columns.Add("Int", typeof(int));
table.Columns.Add("Date", typeof(DateTime));
for (var i = 0; i < rowCount; i++)
{
table.Rows.Add(string.Format("Row {0}", i), i, DateTime.Today.AddDays(i));
}
return table;
}
}
**Form2**
public class Form2 : Form1
{
public Form2()
{
}
public void Display()
{
if (handleCreated)
{
}
//Form1 obj = new Form1();
//if (obj.handleCreated)
//{
//}
}
}
In Form2 handleCreated its always false I dont know why?
please help me

This is because your form2 object is just only initialized. Control will get its handle only after window is created, which displays this control. So, you need to call form2.Show() or form2.ShowDialog() and after that check for gridControl1.IsHandleCreated.
You can simply test this behavior by using this code:
Form2 obj = new Form2();
MessageBox.Show("Created: " + obj.handleCreated);
obj.Show();
MessageBox.Show("Shown: " + obj.handleCreated);

Related

How to upload Multiple file in Kentico Custom BizForm?

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.

Dynamically add static method in aspx page from ascx

i was searching google for that is there any way to add any method in my page at run time. i got a link from stackoverflow for this....that is expando object.
i am not familiar with expando object. here is little snippet of code i got and like
namespace DynamicDemo
{
class ExpandoFun
{
public static void Main()
{
Console.WriteLine("Fun with Expandos...");
dynamic student = new ExpandoObject();
student.FirstName = "John";
student.LastName = "Doe";
student.Introduction=new Action(()=>
Console.WriteLine("Hello my name is {0} {1}",student.FirstName,student.LastName);
);
);
Console.WriteLine(student.FirstName);
student.Introduction();
}
}
}
according to my situation i need to add a routine below like
in many aspx page.
[WebMethod]
public static string LoadData(string CountryCode,int PageIndex)
{
string strData = "";
if (CountryCode != "")
{
strData = Left1.HavingCountry(CountryCode, PageIndex);
}
else
{
strData = Left1.WithoutCountry(PageIndex);
}
return strData;
}
so i need to know that is there any way to add some technique in my ascx page which will add the above method in all the aspx pages which host that particular ascx. please help me to achieve it. thanks
I don't think it is possible.
Can you do this way
1. create a `class` which extents `System.Web.UI.Page`.
2. write you `WebMethod` in that class.
3. Create your aspx pages by extending this class
public partial class _Default : TestUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
public class TestUserControl : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string LoadData(string CountryCode, int PageIndex)
{
string strData = "";
if (CountryCode != "")
{
strData = Left1.HavingCountry(CountryCode, PageIndex);
}
else
{
strData = Left1.WithoutCountry(PageIndex);
}
return strData;
}
}

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

How to maintain state in (asp.net) custom server control?

I am trying to make a custom server control which inherits from DropDownList. I give the control an XML input containing some key/value pairs and my control shows them as a DropDownList.
I make the list items in the override Render method like this:
foreach (XElement child in root.Elements("Choice"))
{
string title = child.Element("Title").Value;
string score = child.Element("Score").Value;
item = new ListItem();
item.Text = title;
item.Value = score;
this.Items.Add(item);
}
The problem is that, when the user selects and item in the list, and the page posts back, the selected item is lost, and the list is re-initialized with the default data.
Does anyone have any idea how to keep the selected item, i.e. maintain the state?
Here is the complete source:
public class MultipleChoiceQuestionView2 : DropDownList
{
public MultipleChoiceQuestionView2() : base()
{
}
protected override void Render(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
#region Parse Contets
if (!String.IsNullOrEmpty(this.Contents))
{
XElement root = XElement.Parse(this.Contents);
if (root.HasAttributes)
{
this.NoOfChoices = Int32.Parse(root.Attribute("ItemCount").Value);
}
this.Items.Clear();
this.Style.Add("width", "100px");
this.Style.Add("font-family", "Tahoma");
this.Items.Clear();
ListItem item = new ListItem();
item.Text = "";
item.Value = "0";
this.Items.Add(item);
foreach (XElement child in root.Elements("Choice"))
{
string title = child.Element("Title").Value;
string score = child.Element("Score").Value;
item = new ListItem();
item.Text = title;
item.Value = score;
this.Items.Add(item);
}
}
#endregion
base.Render(writer);
writer.RenderEndTag();
if (this.Required)
{
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = this.ID;
rfv.InitialValue = "0";
rfv.Text = "*";
if (!String.IsNullOrEmpty(this.ValidationGroup))
{
rfv.ValidationGroup = this.ValidationGroup;
}
writer.RenderBeginTag(HtmlTextWriterTag.Td);
rfv.RenderControl(writer);
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.RenderEndTag();
}
#region Properties
public string Contents
{
get
{
return ViewState["Contents"] == null ? "" : ViewState["Contents"].ToString();
}
set
{
ViewState["Contents"] = value;
}
}
private int mNoOfChoices;
public int NoOfChoices
{
get
{
return mNoOfChoices;
}
set
{
mNoOfChoices = value;
}
}
private string mValidationGroup;
public string ValidationGroup
{
get
{
return mValidationGroup;
}
set
{
mValidationGroup = value;
}
}
public string SelectedChoice
{
get
{
return "";
}
}
private bool mRequired = false;
public bool Required
{
get
{
return mRequired;
}
set
{
mRequired = value;
}
}
#endregion
}
Thanks in advance.
You've got two options: ViewState or ControlState.
The difference being ViewState can be overriden by setting EnableViewState="false" in the page directive, whilst ControlState cannot.
Essentially you need to hook into the state bag when you're getting/setting the values of the dropdown.
There's a decent example here where a custom control is derived from the Button class and maintains state between page requests - should fit your scenario nicely.
Hopefully that gets you started.

MS-Sharepoint 2007: Custom Field Control, TemplateContainer.FindControl always returns NULL

I have SharePoint 2007 on Windows Server 2003 SP1 (in VM).
I am running the web application here: http://vspug.com/nicksevens/2007/08/31/create-custom-field-types-for-sharepoint/
Part of it is below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace CustomControl
{
public class customfieldcontrol : BaseFieldControl
{
protected TextBox txtFirstName;
protected TextBox txtLastName;
protected override string DefaultTemplateName
{
get { return "CustomFieldRendering"; }
}
public override object Value
{
get
{
EnsureChildControls();
return txtFirstName.Text + "%" + txtLastName.Text;
}
set
{
try
{
EnsureChildControls();
txtFirstName.Text = value.ToString().Split('%')[0];
txtLastName.Text = value.ToString().Split('%')[1];
}
catch { }
}
}
public override void Focus()
{
EnsureChildControls();
txtFirstName.Focus();
}
protected override void CreateChildControls()
{
if (Field == null) return;
base.CreateChildControls();
//Don't render the textbox if we are just displaying the field
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display) return;
txtFirstName = (TextBox)TemplateContainer.FindControl("txtFirstName");
txtLastName = (TextBox)TemplateContainer.FindControl("txtLastName");
if (txtFirstName == null) throw new NullReferenceException("txtFirstName is null");
if (txtLastName == null) throw new NullReferenceException("txtLastName is null");
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.New)
{
txtFirstName.Text = "";
txtLastName.Text = "";
}
}
}
}
This line:
txtFirstName = (TextBox)TemplateContainer.FindControl("txtFirstName");
always returns null.
I removed base.CreateChildControls() but it still returns null.
Any assistance would be greatly appreciated.
Place your control's .ascx file right under CONTROLTEMPLATES folder and try.

Resources