Error when using Children.Add in Xamarin Forms - c#

Im having some problems with the Children.Add() function of a Stack Layout. There is an error in the code below which says " There is no argument that corresponds to the required formal parameter 'value' of 'SettersExtentions.Add(IList, Bindable Property, object)' ". The error is a curly red underline under all the .Add words.
public class LoginPage : ContentPage
{
public string email { get; set; }
public string password { get; set; }
Entry emailBox = new Entry();
Entry passwordBox = new Entry();
Button createAccount = new Button();
Button forgotPassword = new Button();
Layout layout = new StackLayout();
public LoginPage()
{
Title = "Login";
emailBox.Placeholder = "email";
passwordBox.Placeholder = "password";
passwordBox.IsPassword = true;
createAccount.Text = "Create Account";
createAccount.Font = Font.SystemFontOfSize(NamedSize.Large);
createAccount.BorderWidth = 1;
createAccount.HorizontalOptions = LayoutOptions.Center;
createAccount.VerticalOptions = LayoutOptions.CenterAndExpand;
forgotPassword.Text = "Forgot Password";
forgotPassword.Font = Font.SystemFontOfSize(NamedSize.Large);
forgotPassword.BorderWidth = 1;
forgotPassword.HorizontalOptions = LayoutOptions.Center;
forgotPassword.VerticalOptions = LayoutOptions.CenterAndExpand;
layout.VerticalOptions = LayoutOptions.CenterAndExpand;
layout.Children.Add(emailBox);
layout.Children.Add(passwordBox);
layout.Children.Add(createAccount);
layout.Children.Add(forgotPassword);
Content = layout;
}
public void Check(string email, string password, string cpassword)
{
}
}

Layout.Children is a readonly IReadOnlyList<Element> so you wont be able to add to it.
However StackLayout.Children is IList<T> which will allow you to add children
change
Layout layout = new StackLayout();
to
StackLayout layout = new StackLayout();
This will allow you to be able to add the child elements to the layout.

Related

Android C# Clear TextView before populating with new data

I'm trying to clear 3 TextView fields before new data is then displayed. I'm using SQLite and returning 3 phone numbers.
I can't run the app as I get "cannot convert from string to int" on the
txtFire.SetText("");
section of code.
The 3 fields in my SQLite DB are TEXT fields, so slightly confused on how to resolve this.
Any advice is appreciated.
private void EmergencyServicesData()
{
var location = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteCountry).Text;
ICursor selectData = sqliteDB.RawQuery("SELECT POLICE, FIRE, MEDICAL FROM EmergencyServices WHERE COUNTRY = '" + location + "'", new string[] { });
if (selectData.Count > 0)
{
selectData.MoveToFirst();
do
{
txtFire = (TextView)FindViewById(Resource.Id.txtFire);
txtMedical = (TextView)FindViewById(Resource.Id.txtMedical);
txtPolice = (TextView)FindViewById(Resource.Id.txtPolice);
txtFire.SetText("");
txtMedical.SetText("");
txtPolice.SetText("");
EmergencyServices emergencyServices = new EmergencyServices();
EmergencyServices.Clear();
emergencyServices.POLICE = selectData.GetString(selectData.GetColumnIndex("POLICE"));
emergencyServices.FIRE = selectData.GetString(selectData.GetColumnIndex("FIRE"));
emergencyServices.MEDICAL = selectData.GetString(selectData.GetColumnIndex("MEDICAL"));
EmergencyServices.Add(emergencyServices);
}
while (selectData.MoveToNext());
selectData.Close();
}
foreach (var item in EmergencyServices)
{
LayoutInflater layoutInflater = (LayoutInflater)BaseContext.GetSystemService(Context.LayoutInflaterService);
View addView = layoutInflater.Inflate(Resource.Layout.EmergencyServices, null);
TextView txtPoliceData = addView.FindViewById<TextView>(Resource.Id.txtPolice);
TextView txtFireData = addView.FindViewById<TextView>(Resource.Id.txtFire);
TextView txtMedicalData = addView.FindViewById<TextView>(Resource.Id.txtMedical);
txtPoliceData.Text = item.POLICE;
txtFireData.Text = item.FIRE;
txtMedicalData.Text = item.MEDICAL;
container.AddView(addView);
}
}
You have nullpointers in your textviews. Change to this.
LayoutInflater layoutInflater = (LayoutInflater)BaseContext.GetSystemService(Context.LayoutInflaterService);
View addView = layoutInflater.Inflate(Resource.Layout.EmergencyServices, null);
txtFire = addView.FindViewById<TextView>(Resource.Id.txtFire);
txtMedical = addView.FindViewById<TextView>(Resource.Id.txtMedical);
txtPolice = addView.FindViewById<TextView>(Resource.Id.txtPolice);

Children.Add() in Xamarin Forms

im really new to c# and Xamarin Forms but can someone please explain to me why I'm getting an error in the last line of code below ?
Visual Studio is indicating a curly red underline on the word Children on the last line of this code indicating that there is some syntax error but I don't see why that is an error since I'm just accessing a member of the class ....
var content = new ContentPage();
content.Title = "Appuler";
Label CompanyName = new Label();
CompanyName.HorizontalTextAlignment = TextAlignment.Center;
CompanyName.Text = "Test";
Button NextPage = new Button();
NextPage.Text = "Next Page";
NextPage.Font = Font.SystemFontOfSize(NamedSize.Large);
NextPage.BorderWidth = 1;
NextPage.HorizontalOptions = LayoutOptions.Center;
NextPage.VerticalOptions = LayoutOptions.CenterAndExpand;
content.Content = new StackLayout();
content.Content.VerticalOptions = LayoutOptions.CenterAndExpand;
content.Content.Children.Add(CompanyName);
Refactor the last few lines to the following
var layout = new StackLayout();
layout.VerticalOptions = LayoutOptions.CenterAndExpand;
layout.Children.Add(CompanyName);
content.Content = layout;
ContentPage.Content does not have that Children property as it is a View. StackLayout, however does have a Children property that can be accessed.
populate the layout control's accessible properties and then assign it to the Content property of the ContentPage.

how to create a button dynamically in xamarin c# according to number of data in database. ln my code linear layout declaration is not working

I'm trying to create a button dynamically in xamarin c# according to number of data in database.After linear layout declaration entire code is not working.
try
{ var client = new System.Net.Http.HttpClient();
var response = await client.GetAsync("http://");
string jsonResponse = await response.Content.ReadAsStringAsync();
JSONArray a = new JSONArray(jsonResponse);
LinearLayout linearLayout = FindViewById<LinearLayout>(Resource.Id.linearlayout1);
for (int i = 0; i < a.Length(); i++)
{
JSONObject json = a.GetJSONObject(i);
String id = json.GetString("id");
String name = json.GetString("name");
String status = json.GetString("status");
// Toast.MakeText(this, id + name + status, ToastLength.Long).Show();
Button button = new Button(this);
button.Text = name;
button.SetBackgroundColor(Android.Graphics.Color.Black);
button.SetTextColor(Android.Graphics.Color.White);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
layoutParams.BottomMargin = 5;
button.LayoutParameters = layoutParams;
//Toast.MakeText(this, id, ToastLength.Long).Show();
linearLayout.AddView(button);
}
}
catch (Exception e)
{
Toast.MakeText(this, "Excep", ToastLength.Long).Show();
}
Doesn't look like you're adding it to your view as children.
Here's something:
//You need a ViewGroup, you already have it:
LinearLayout linearLayout = FindViewById<LinearLayout>(Resource.Id.linearLayout1);
for (int i = 0; i < a.Length(); i++)
{
JSONObject json = a.GetJSONObject(i);
String id = json.GetString("id");
String name = json.GetString("name");
String status = json.GetString("status");
//You create the instance of your view in this case your Button
Button button = new Button(this);
button.Text = name;
button.SetBackgroundColor(Android.Graphics.Color.Black);
button.SetTextColor(Android.Graphics.Color.White);
//define the button layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
//in case you want to modify other properties of the LayoutParams you use the object
layoutParams.BottomMargin = 5;
//Assign the layoutParams to the Button.
button.LayoutParameters = layoutParams;
//If you want to do something with the buttons you create you add the handle here
//button.Click += (sender, e) => DoSomething(id);
//Add the button as a child of your ViewGroup
linearLayout.AddView(button);
}
And you are done. This should guide you.

Checkbox turning multiple values true

I've been stuck of this for a while and would love some insight.
When I add a new user or source and check the drawn checkbox, it causes the bool to be true when checked, as expected.
However it also checks all the other users connected to that source as true or false.
[before]
[after]
This only occurs when I load the XML file into my program that already had existing data, then add new Users or Sources via the UI.
this is a part of the LoadXML Method.
// Load the source list
sourceProps.SystemSources.Clear();
fCMUserSourceBindingSource.Clear();
fCMSourceBindingSource.Clear();
foreach (FusionSource src in fusionSystem.sourceList)
{
FCMSource fSource = new FCMSource(src);
sourceProps.SystemSources.Add(fSource);
fCMSourceBindingSource.Add(fSource);
fCMUserSourceBindingSource.Add(fSource);
}
txtSourceID.Text = sourceProps.GenerateNextSourceId();
// Load the user data from the fusionSystem object.
userProfile.SystemUserList.Clear();
//currently clears grid. might need to clear list instead
fCMUserBindingSource.Clear();
foreach (FusionUser usr in fusionSystem.userList)
{
FCMUser fUser = new FCMUser(usr);
userProfile.SystemUserList.Add(fUser);
fCMUserBindingSource.Add(fUser);
foreach (FusionSourcePermission srcPerm in usr.SourcePermissionList)
{
FCMSource fSource = new FCMSource(srcPerm);
fUser.fusionUserSources.Add(fSource);
}
}
AddColumnsUsersToSourceAllocation();
txtUserID.Text = userProfile.GenerateNextUserId();
// Load the zone group data from the fusionSystem object
zoneProps.systemZoneGroupList.Clear();
fCMZoneGroupBindingSource.Clear();
Any help would be appreciated.
Edit
The ListView is not binded and all the 'checking' is done programmatically when the user activates the click event.
private void lstSourceToUser_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if (e.ColumnIndex > 1)
{
int usrIndex = userProfile.GetUserIndexByID(e.Header.Name);
int srcIndex = userProfile.GetUsersSourceIndex(e.Header.Name, e.Item.SubItems[0].Text);
Graphics g = e.Graphics;
CheckBoxRenderer.DrawCheckBox(g,new Point((e.Bounds.X + e.Bounds.Width/2 -10 ),(e.Bounds.Y)), userProfile.SystemUserList[usrIndex].fusionUserSources[srcIndex].UserSourceChkBox.MyCheckedState ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
}
else
// Draw the other subitems with default drawing.
e.DrawDefault = true;
}
Edit
This is the FCMSource constructor.
public FCMSource(string sourceId, string sourceName, string icnId, string lstIndx)
{
id = sourceId;
icon = icnId;
name = sourceName;
listIndex = lstIndx;
UserSourceCheckState = false;
UserSourceChkBox = new MyCheckBoxItem(false);
}
public FCMSource(FCMSource fSource, bool chk)
{
name = fSource.name;
icon = fSource.icon;
id = fSource.id;
listIndex = fSource.listIndex;
UserSourceCheckState = chk ? true : false;
UserSourceChkBox = new MyCheckBoxItem(chk);
}
And this is the FCMUser constructor which contains the different Sources.
public FCMUser(string userid, string nm, string icn, string pinNo, CheckBox pinEn, string lstIndx)
{
id = userid;
name = nm;
icon = icn;
pin = pinNo;
pinEnabled = pinEn.CheckState;
chkBoxPINEnable = new MyCheckBoxItem(false);
fusionUserSources = new List<FCMSource>();
ListIndex = lstIndx;
updateCheckbox();
}

Failed to load viewstate with a composite control

I have created a composite control that changes the controls in it based on the value of one of it's properties called "Type".
The intent is that once this "Type" property is set, it is not changed again for the life of the control, so the controls rendered as a result of the value of the "Type" property should not change.
I have overridden the LoadViewState and SaveViewState methods as recommended on by many internet posts, but I am still getting an error about "Failed to Load ViewState". The control will render appropriately on the first load, but once any postback is made, it generates the "Failed to Load ViewState" error.
Here is part of the code for the composite control:
[Serializable]
internal enum SearchPanelControlType
{
Label,
DropDownList,
TextBox
}
[Serializable]
internal class SearchGridViewStateObject<T> where T : Bll.BaseCriteria
{
public T mySearchCriteria { get; set; }
public SearchGridType myType { get; set; }
public int myNumberOfChildrenPerRow { get; set; }
public object myBaseViewState { get; set; }
public SearchGridViewStateObject(T searchCriteria, SearchGridType type, int numberOfChildrenPerRow, object baseViewState)
{
mySearchCriteria = searchCriteria;
myType = type;
myNumberOfChildrenPerRow = numberOfChildrenPerRow;
myBaseViewState = baseViewState;
}
}
[Themeable(true)]
[Serializable]
public class SearchGrid<T> : CompositeControl
where T : Bll.BaseCriteria
{
#region Constructor
public SearchGrid()
{
}
#endregion
#region Private Fields
private MyCompanygridview myGridView;
private ObjectDataSource myObjectDataSource;
private Panel mySearchParametersPanel;
private Button mySearchButton;
private Button myClearSearchCriteriaButton;
private T mySearchCriteria;
//private SearchGridType myType = SearchGridType.Account;
private SearchGridType myType;
private int myNumberOfChildrenPerRow = 2;
private MyCompanygridviewSelectionType mySelectionType = MyCompanygridviewSelectionType.None;
private int mySelectColumnIndex = 0;
private int myPageSize = 10;
private int myPageIndex = 0;
private string myGridViewCssClass;
private string myCustomPagerButtonCssClass;
private string myCustomPagerTextBoxCssClass;
private string myRowCssClass;
private string myEmptyDataRowCssClass;
private string myPagerCssClass;
private string mySelectedRowCssClass;
private string myHeaderCssClass;
private string myAlternatingRowCssClass;
private string myDisabledRowCssClass;
private List<Guid> myGridViewDisabledValues = new List<Guid>();
private List<Guid> myGridViewSelectedValues = new List<Guid>();
private GridLines myGridLines = GridLines.None;
private string mySearchPanelButtonCssClass;
private string mySearchPanelTextBoxCssClass;
private string mySearchPanelDropDownListCssClass;
private string mySearchPanelLabelCssClass;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the search criteria.
/// </summary>
/// <value>The search criteria.</value>
public T SearchCriteria
{
get
{
return mySearchCriteria;
}
set
{
if (value != mySearchCriteria)
{
mySearchCriteria = value;
this.ChildControlsCreated = false;
this.EnsureChildControls();
}
}
}
/// <summary>
/// Gets or sets the type of items that should be shown in the gridview.
/// </summary>
/// <summary>
/// Gets or sets the type of items that should be shown in the gridview.
/// </summary>
[Category("SearchGrid"),
Description("Gets or sets the type of items that should be shown in the grid view."),
DefaultValue(null)]
public SearchGridType Type
{
get
{
return myType;
}
set
{
if (value != myType)
{
myType = value;
this.ChildControlsCreated = false;
this.EnsureChildControls();
}
}
}
[DefaultValue(MyCompanygridviewSelectionType.None),
Category("SearchGrid"),
Description("Indicates whether to use multiselection mode, single selection mode, or no selection mode.")]
public MyCompanygridviewSelectionType SelectionType
{
get
{
return mySelectionType;
}
set
{
mySelectionType = value;
}
}
#endregion
#region Overridden Methods
protected override void LoadViewState(object savedState)
{
SearchGridViewStateObject<T> vsObject = savedState as SearchGridViewStateObject<T>;
mySearchCriteria = vsObject.mySearchCriteria;
myType = vsObject.myType;
myNumberOfChildrenPerRow = vsObject.myNumberOfChildrenPerRow;
ClearChildViewState();
this.ChildControlsCreated = false;
this.EnsureChildControls();
base.LoadViewState(vsObject.myBaseViewState);
}
protected override object SaveViewState()
{
SearchGridViewStateObject<T> vsObject = new SearchGridViewStateObject<T>(mySearchCriteria, myType, myNumberOfChildrenPerRow, base.SaveViewState());
return vsObject;
}
protected override void RecreateChildControls()
{
EnsureChildControls();
}
protected override void CreateChildControls()
{
SearchGridParser parser = SearchGridParserFactory.GetParser(this.myType);
Controls.Clear();
//Define the Search Parameters Panel
mySearchParametersPanel = new Panel();
mySearchParametersPanel.ID = "spp" + Enum.GetName(typeof(SearchGridType), this.myType);
mySearchParametersPanel.DefaultButton = "btnSearch";
mySearchParametersPanel.ScrollBars = ScrollBars.None;
parser.CreateSearchPanelControls(ref mySearchParametersPanel, CreateSearchPanelStyleDictionary());
//Define Buttons
mySearchButton = new Button();
mySearchButton.ID = "btnSearch";
mySearchButton.Text = "Search";
mySearchButton.CausesValidation = false;
mySearchButton.UseSubmitBehavior = false;
mySearchButton.Click += new EventHandler(mySearchButton_Click);
if (!string.IsNullOrEmpty(mySearchPanelButtonCssClass))
{
mySearchButton.CssClass = mySearchPanelButtonCssClass;
}
myClearSearchCriteriaButton = new Button();
myClearSearchCriteriaButton.ID = "btnClearSearchCriteria";
myClearSearchCriteriaButton.Text = "Clear Search Criteria";
myClearSearchCriteriaButton.CausesValidation = false;
myClearSearchCriteriaButton.UseSubmitBehavior = false;
myClearSearchCriteriaButton.Click += new EventHandler(myClearSearchCriteriaButton_Click);
if (!string.IsNullOrEmpty(mySearchPanelButtonCssClass))
{
myClearSearchCriteriaButton.CssClass = mySearchPanelButtonCssClass;
}
mySearchParametersPanel.Controls.Add(mySearchButton);
mySearchParametersPanel.Controls.Add(myClearSearchCriteriaButton);
// Define the GridView
myGridView = new MyCompanygridview();
myGridView.ID = "gv" + Enum.GetName(typeof(SearchGridType), this.myType);
myGridView.AutoGenerateColumns = false;
myGridView.DataKeyNames = new string[] { "ID" };
myGridView.DataSourceID = "ods" + Enum.GetName(typeof(SearchGridType), this.myType);
myGridView.AllowSorting = true;
myGridView.Width = new System.Web.UI.WebControls.Unit("100%");
myGridView.AllowPaging = true;
myGridView.EnableCustomPager = true;
myGridView.Sorted += new EventHandler(myGridView_Sorted);
myGridView.PageIndexChanged += new EventHandler(myGridView_PageIndexChanged);
myGridView.PageSizeChanged += new EventHandler(myGridView_PageSizeChanged);
myGridView.PageSizeChanging += new EventHandler(myGridView_PageSizeChanging);
myGridView.SelectionType = this.mySelectionType;
myGridView.SelectColumnIndex = this.mySelectColumnIndex;
myGridView.PageSize = this.myPageSize;
myGridView.PageIndex = this.myPageIndex;
myGridView.CssClass = this.myGridViewCssClass;
myGridView.CustomPagerButtonCssStyle = this.myCustomPagerButtonCssClass;
myGridView.CustomPagerTextBoxCssStyle = this.myCustomPagerTextBoxCssClass;
myGridView.RowStyle.CssClass = this.myRowCssClass;
myGridView.EmptyDataRowStyle.CssClass = this.myEmptyDataRowCssClass;
myGridView.PagerStyle.CssClass = this.myPagerCssClass;
myGridView.SelectedRowStyle.CssClass = this.mySelectedRowCssClass;
myGridView.HeaderStyle.CssClass = this.myHeaderCssClass;
myGridView.AlternatingRowStyle.CssClass = this.myAlternatingRowCssClass;
myGridView.DisabledRowCssClass = this.myDisabledRowCssClass;
myGridView.DisabledValues = this.myGridViewDisabledValues;
myGridView.SelectedValues = this.myGridViewSelectedValues;
myGridView.GridLines = this.myGridLines;
parser.CreateGridViewColumns(ref myGridView);
// Define the object data source
myObjectDataSource = new ObjectDataSource();
myObjectDataSource.ID = "ods" + Enum.GetName(typeof(SearchGridType), this.myType);
myObjectDataSource.OldValuesParameterFormatString = "original_{0}";
myObjectDataSource.SelectMethod = "GetList";
myObjectDataSource.SelectCountMethod = "SelectCountForGetList";
myObjectDataSource.TypeName = "MyCompany.DCO.MyProject.Bll." + Enum.GetName(typeof(SearchGridType), this.myType) + "Manager";
myObjectDataSource.EnablePaging = true;
myObjectDataSource.StartRowIndexParameterName = "startRowIndex";
myObjectDataSource.MaximumRowsParameterName = "maximumRows";
myObjectDataSource.SortParameterName = "SortExpression";
myObjectDataSource.Selecting += new ObjectDataSourceSelectingEventHandler(myObjectDataSource_Selecting);
myObjectDataSource.Selected += new ObjectDataSourceStatusEventHandler(myObjectDataSource_Selected);
// Add the defined controls
this.Controls.Add(myObjectDataSource);
this.Controls.Add(myGridView);
this.Controls.Add(mySearchParametersPanel);
parser.SetSearchPanelControls<T>(this.mySearchCriteria, ref mySearchParametersPanel);
}
protected override void Render(HtmlTextWriter writer)
{
AddAttributesToRender(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
mySearchParametersPanel.RenderControl(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Br);
writer.RenderEndTag();
myGridView.RenderControl(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Br);
writer.RenderEndTag();
myObjectDataSource.RenderControl(writer);
writer.RenderEndTag();
}
#endregion
}
Here is the code for the "parser" file that creates the custom controls:
class SearchGridParser_ApplicationFunction : SearchGridParser
{
internal override void CreateGridViewColumns(ref MyCompanygridview myGridView)
{
// Link Column
HyperLinkField linkColumn = new HyperLinkField();
linkColumn.Text = "Edit";
linkColumn.HeaderText = "ID";
linkColumn.DataNavigateUrlFields = new string[] { "ID" };
linkColumn.DataNavigateUrlFormatString = "~/AddEdit/ApplicationFunction/default.aspx?Action=Edit&ID={0}";
myGridView.Columns.Add(linkColumn);
// Name Column
BoundField nameColumn = new BoundField();
nameColumn.DataField = "Name";
nameColumn.HeaderText = "Name";
nameColumn.SortExpression = "Name";
myGridView.Columns.Add(nameColumn);
// Description Column
BoundField descriptionColumn = new BoundField();
descriptionColumn.DataField = "Description";
descriptionColumn.HeaderText = "Description";
descriptionColumn.SortExpression = "Description";
myGridView.Columns.Add(descriptionColumn);
// Business Criticality Column
TemplateField businessCriticalityColumn = new TemplateField();
businessCriticalityColumn.SortExpression = "BusinessCriticality";
businessCriticalityColumn.HeaderText = "Criticality";
businessCriticalityColumn.ItemTemplate = new LabelColumnGridViewTemplate(ListItemType.Item, "BusinessCriticality", "Name");
myGridView.Columns.Add(businessCriticalityColumn);
// Disabled Column
CheckBoxField disabledColumn = new CheckBoxField();
disabledColumn.DataField = "DisabledFlg";
disabledColumn.HeaderText = "Disabled";
disabledColumn.SortExpression = "DisabledFlg";
myGridView.Columns.Add(disabledColumn);
// Agencies Column
TemplateField agenciesColumn = new TemplateField();
agenciesColumn.HeaderText = "Agencies";
agenciesColumn.ItemTemplate = new ChildObjectsGridViewTemplate(ListItemType.Item, 2, "Agencies", "Agency.Abbreviation");
myGridView.Columns.Add(agenciesColumn);
// Applications Column
TemplateField applicationsColumn = new TemplateField();
applicationsColumn.HeaderText = "Applications";
applicationsColumn.ItemTemplate = new ChildObjectsGridViewTemplate(ListItemType.Item, 2, "Applications", "Application.Name");
myGridView.Columns.Add(applicationsColumn);
}
internal override void CreateSearchPanelControls(ref Panel myPanel, Dictionary<SearchPanelControlType, string> myStyleDictionary)
{
if (myStyleDictionary == null)
{
myStyleDictionary = new Dictionary<SearchPanelControlType, string>();
}
// Title
Literal myTitleStart = new Literal();
myTitleStart.Text = "<h4>";
Label myTitle = new Label();
myTitle.Text = "Application Function:";
myTitle.ID = "lblTitle";
Literal myTitleEnd = new Literal();
myTitleEnd.Text = "</h4>";
// Begin Table
Table myTable = new Table();
myTable.ID = "myTable";
// Create First Row
TableRow myTableRow1 = new TableRow();
myTableRow1.ID = "myTableRow1";
// Search by Name
TableCell myNameLabelTableCell = new TableCell();
myNameLabelTableCell.ID = "myNameLabelTableCell";
Label myNameLabel = new Label();
myNameLabel.ID = "lblName";
myNameLabel.Text = "Name:";
myNameLabel.AssociatedControlID = "txtName";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myNameLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myNameLabelTableCell.Controls.Add(myNameLabel);
myTableRow1.Cells.Add(myNameLabelTableCell);
TableCell myNameUserInputTableCell = new TableCell();
myNameUserInputTableCell.ID = "myNameUserInputTableCell";
TextBox myNameTextBox = new TextBox();
myNameTextBox.ID = "txtName";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.TextBox))
{
myNameTextBox.CssClass = myStyleDictionary[SearchPanelControlType.TextBox];
}
myNameUserInputTableCell.Controls.Add(myNameTextBox);
myTableRow1.Cells.Add(myNameUserInputTableCell);
// Search by Agency
TableCell myAgencyLabelTableCell = new TableCell();
myAgencyLabelTableCell.ID = "myAgencyLabelTableCell";
Label myAgencyLabel = new Label();
myAgencyLabel.ID = "lblAgency";
myAgencyLabel.Text = "Agency:";
myAgencyLabel.AssociatedControlID = "ddlAgency";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myAgencyLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myAgencyLabelTableCell.Controls.Add(myAgencyLabel);
myTableRow1.Cells.Add(myAgencyLabelTableCell);
TableCell myAgencyUserInputTableCell = new TableCell();
myAgencyUserInputTableCell.ID = "myAgencyUserInputTableCell";
DropDownList<AgencyCriteria> myAgencyDDL = new DropDownList<AgencyCriteria>();
myAgencyDDL.Type = DropDownListType.Agency;
myAgencyDDL.ID = "ddlAgency";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
{
myAgencyDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
}
myAgencyDDL.DisplayDisabled = true;
myAgencyDDL.EnableAnyOption = true;
myAgencyDDL.DataBind();
myAgencyUserInputTableCell.Controls.Add(myAgencyDDL);
myTableRow1.Cells.Add(myAgencyUserInputTableCell);
myTable.Rows.Add(myTableRow1);
// Create Second row
TableRow myTableRow2 = new TableRow();
myTableRow2.ID = "myTableRow2";
// Search by BusinessCriticality
TableCell myBusinessCriticalityLabelTableCell = new TableCell();
myBusinessCriticalityLabelTableCell.ID = "myBusinessCriticalityLabelTableCell";
Label myBusinessCriticalityLabel = new Label();
myBusinessCriticalityLabel.ID = "lblBusinessCriticality";
myBusinessCriticalityLabel.Text = "Criticality:";
myBusinessCriticalityLabel.AssociatedControlID = "ddlBusinessCriticality";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myBusinessCriticalityLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myBusinessCriticalityLabelTableCell.Controls.Add(myBusinessCriticalityLabel);
myTableRow2.Cells.Add(myBusinessCriticalityLabelTableCell);
TableCell myBusinessCriticalityUserInputTableCell = new TableCell();
myBusinessCriticalityUserInputTableCell.ID = "myBusinessCriticalityUserInputTableCell";
DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = new DropDownList<LookupCodeCriteria>();
myBusinessCriticalityDDL.Type = DropDownListType.LookupCode;
myBusinessCriticalityDDL.ID = "ddlBusinessCriticality";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
{
myBusinessCriticalityDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
}
myBusinessCriticalityDDL.DisplayDisabled = true;
myBusinessCriticalityDDL.EnableAnyOption = true;
LookupCodeCriteria myBusinessCriticalityCriteria = new LookupCodeCriteria();
myBusinessCriticalityCriteria.Type = LookupCodeType.BusinessCriticality;
myBusinessCriticalityDDL.OtherCriteria = myBusinessCriticalityCriteria;
myBusinessCriticalityDDL.DataBind();
myBusinessCriticalityUserInputTableCell.Controls.Add(myBusinessCriticalityDDL);
myTableRow2.Cells.Add(myBusinessCriticalityUserInputTableCell);
// Search by DisabledFlg
TableCell myDisabledFlgLabelTableCell = new TableCell();
myDisabledFlgLabelTableCell.ID = "myDisabledFlgLabelTableCell";
Label myDisabledFlgLabel = new Label();
myDisabledFlgLabel.ID = "lblDisabledFlg";
myDisabledFlgLabel.Text = "Disabled:";
myDisabledFlgLabel.AssociatedControlID = "ddlDisabledFlg";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
{
myDisabledFlgLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
}
myDisabledFlgLabelTableCell.Controls.Add(myDisabledFlgLabel);
myTableRow2.Cells.Add(myDisabledFlgLabelTableCell);
TableCell myDisabledFlgUserInputTableCell = new TableCell();
myDisabledFlgUserInputTableCell.ID = "myDisabledFlgUserInputTableCell";
YesNoAnyDropDownList myDisabledFlgDDL = new YesNoAnyDropDownList();
myDisabledFlgDDL.ID = "ddlDisabledFlg";
if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
{
myDisabledFlgDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
}
myDisabledFlgDDL.DataBind();
myDisabledFlgUserInputTableCell.Controls.Add(myDisabledFlgDDL);
myTableRow2.Cells.Add(myDisabledFlgUserInputTableCell);
myTable.Rows.Add(myTableRow2);
myPanel.Controls.Add(myTitleStart);
myPanel.Controls.Add(myTitle);
myPanel.Controls.Add(myTitleEnd);
myPanel.Controls.Add(myTable);
}
internal override void FillSearchCriteria<T>(T myCriteria, ref Panel myPanel)
{
ApplicationFunctionCriteria derivedCriteria = new ApplicationFunctionCriteria();
if (myCriteria != null)
{
derivedCriteria = myCriteria as ApplicationFunctionCriteria;
}
// Name
TextBox myNameTextBox = (TextBox)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myNameUserInputTableCell").FindControl("txtName");
if (!string.IsNullOrEmpty(myNameTextBox.Text.Trim()))
{
derivedCriteria.Name = myNameTextBox.Text.Trim();
}
else
{
derivedCriteria.Name = string.Empty;
}
// AgencyID
DropDownList<AgencyCriteria> myAgencyDDL = (DropDownList<AgencyCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myAgencyUserInputTableCell").FindControl("ddlAgency");
Guid myAgencyID;
if (myAgencyDDL.SelectedValue.TryParseGuid(out myAgencyID))
{
derivedCriteria.AgencyID = myAgencyID;
}
else
{
derivedCriteria.AgencyID = null;
}
// BusinessCriticalityID
DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = (DropDownList<LookupCodeCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myBusinessCriticalityUserInputTableCell").FindControl("ddlBusinessCriticality");
Guid myBusinessCriticalityID;
if (myBusinessCriticalityDDL.SelectedValue.TryParseGuid(out myBusinessCriticalityID))
{
derivedCriteria.BusinessCriticalityID = myBusinessCriticalityID;
}
else
{
derivedCriteria.BusinessCriticalityID = null;
}
// DisabledFlg
YesNoAnyDropDownList myDisabledFlgDDL = (YesNoAnyDropDownList)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myDisabledFlgUserInputTableCell").FindControl("ddlDisabledFlg");
bool myDisabledFlg;
if (bool.TryParse(myDisabledFlgDDL.SelectedValue, out myDisabledFlg))
{
derivedCriteria.DisabledFlg = myDisabledFlg;
}
else
{
derivedCriteria.DisabledFlg = null;
}
}
internal override void SetSearchPanelControls<T>(T myCriteria, ref Panel myPanel)
{
ApplicationFunctionCriteria derivedCriteria = new ApplicationFunctionCriteria();
if (myCriteria != null)
{
derivedCriteria = myCriteria as ApplicationFunctionCriteria;
}
// Name
TextBox myNameTextBox = (TextBox)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myNameUserInputTableCell").FindControl("txtName");
myNameTextBox.Text = derivedCriteria.Name;
// AgencyID
DropDownList<AgencyCriteria> myAgencyDDL = (DropDownList<AgencyCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myAgencyUserInputTableCell").FindControl("ddlAgency");
if (derivedCriteria.AgencyID.HasValue)
{
myAgencyDDL.SelectedValue = derivedCriteria.AgencyID.ToString();
}
else
{
myAgencyDDL.SelectedValue = "0";
}
// BusinessCriticalityID
DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = (DropDownList<LookupCodeCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myBusinessCriticalityUserInputTableCell").FindControl("ddlBusinessCriticality");
if (derivedCriteria.BusinessCriticalityID.HasValue)
{
myBusinessCriticalityDDL.SelectedValue = derivedCriteria.BusinessCriticalityID.ToString();
}
else
{
myBusinessCriticalityDDL.SelectedValue = "0";
}
// DisabledFlg
YesNoAnyDropDownList myDisabledFlgDDL = (YesNoAnyDropDownList)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myDisabledFlgUserInputTableCell").FindControl("ddlDisabledFlg");
if (derivedCriteria.DisabledFlg.HasValue)
{
myDisabledFlgDDL.SelectedValue = derivedCriteria.DisabledFlg.ToString();
}
else
{
myDisabledFlgDDL.SelectedValue = "any";
}
}
}
Here is the code on the aspx page I am using to test the control:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
And the codebehind:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomWebControls.SearchGrid<AccountCriteria> myAppFuncGrid = new MyCompany.DCO.MyProject.CustomWebControls.SearchGrid<AccountCriteria>();
myAppFuncGrid.Type = MyCompany.DCO.MyProject.CustomWebControls.SearchGridType.Account;
myAppFuncGrid.SelectionType = MyCompany.DCO.Library.WebControls.MyCompanygridviewSelectionType.Multiple;
myAppFuncGrid.PageSize = 3;
PlaceHolder1.Controls.Add(myAppFuncGrid);
}
}
I've tried only putting the control in if (!Page.IsPostBack) as well, but then it just doesn't even display the control at all on Postback. What am I doing wrong?
UPDATE:
So I added this to the composite control:
protected override void OnInit(EventArgs e)
{
this.CreateChildControls(); base.OnInit(e);
}
And now I no longer get the "failed to load viewstate" error, but it seems that the viewstate of the child controls is not saved across postbacks. One of the controls in my composite control is a gridview with paging enabled and when clicking on next page it will go to page two, but never to page 3 or 4 or so on. But it will go to "last page", "first page" without a problem. But Next Page and Previous Page do no work correctly, but it doesn't throw an error either. Ideas?
When adding your control dynamically to your page, try overriding OnInit or CreateChildControls and doing it in there.
Viewstate is loaded in the pre-load stage and therefore it cannot load viewstate for your controls as they dont yet exist...

Categories