Failed to load viewstate with a composite control - c#

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...

Related

Xamarin C# - What is the fastest way to refresh a gridview every second

I have a problem.
In my Android app I use a: Android.Support.V4.View.ViewPager to swap between a summary and a wallet. The summary page is filled with 3 TextViews and the Wallet is created with 1 GridView. Both the pages are getting filled with data from a HTTPS call from where the response will be parsed into a List. Now I want to refresh both the pages every second. So I tried this:
public void LoadOrderPage()
{
Android.Support.V4.View.ViewPager SummaryWalletSwitcher = FindViewById<Android.Support.V4.View.ViewPager>(Resource.Id.SummaryWalletSwitcher);
List<View> viewlist = new List<View>();
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentSummary, null, false));
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentWallet, null, false));
SummaryWalletAdapter ViewSwitchAdapter = new SummaryWalletAdapter(viewlist);
SummaryWalletSwitcher.Adapter = ViewSwitchAdapter;
Timer AgentInfo_Timer = new Timer();
AgentInfo_Timer.Interval = 1000;
AgentInfo_Timer.Elapsed += LoadAgentInfo;
AgentInfo_Timer.Enabled = true;
}
public void LoadAgentInfo(object sender, ElapsedEventArgs e)
{
TextView TextPortfolioValue = FindViewById<TextView>(Resource.Id.txtPortfolioValue);
TextView TextValueUSDT = FindViewById<TextView>(Resource.Id.txtValueUSDT);
TextView TextTotalValue = FindViewById<TextView>(Resource.Id.txtTotalValue);
GridView GridviewWallet = FindViewById<GridView>(Resource.Id.GridviewWallet);
if (FirstWalletRun == true)
{
List<wallet> EmptyWalletList = new List<wallet>();
WalletListAdapter = new WalletListAdapter(this, EmptyWalletList);
GridviewWallet.Adapter = WalletListAdapter;
FirstWalletRun = false;
}
PortfolioValue = 0;
ValueUSDT = 0;
TotalValue = 0;
string response = "";
AgentId = getSelectedAgentId();
if (AgentId == 0)
{
AgentId = 1;
}
try
{
WebClient client = new WebClient();
var reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("agentid", AgentId.ToString());
reqparm.Add("devicetoken", DeviceToken);
byte[] responsebytes = client.UploadValues("https://www.test.nl/getagentwallet.php", "POST", reqparm);
IgnoreBadCertificates();
response = Encoding.UTF8.GetString(responsebytes);
response = response.Replace("\n", "").Replace("\t", "");
}
catch (Exception ex)
{
string exFullName = (ex.GetType().FullName);
string ExceptionString = (ex.GetBaseException().ToString());
TextPortfolioValue.Text = "Unknown";
TextValueUSDT.Text = "Unknown";
TextTotalValue.Text = "Unknown";
}
if (response != "No updates")
{
//Parse json content
var jObject = JObject.Parse(response);
//Create Array from everything inside Node:"Coins"
var walletPropery = jObject["Wallet"] as JArray;
//Create List to save Coin Data
walletList = new List<wallet>();
//Find every value in Array: coinPropery
foreach (var property in walletPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<wallet>>(property.ToString());
//Add all strings to List
walletList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = walletList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Coin, i.Quantity.ToString(), i.AvgPrice.ToString(), i.Value.ToString() })
.Distinct()
.ToArray();
foreach (string[] str in NamesArray)
{
if (str[1] != "USDT")
{
PortfolioValue += decimal.Parse(str[4]);
}
else
{
ValueUSDT += decimal.Parse(str[4]);
}
}
TotalValue = PortfolioValue + ValueUSDT;
TextPortfolioValue.Text = Math.Round(PortfolioValue, 8).ToString();
TextValueUSDT.Text = Math.Round(ValueUSDT, 8).ToString();
TextTotalValue.Text = Math.Round(TotalValue, 8).ToString();
SortedWalletList = walletList.OrderBy(o => o.Coin).ToList();
if (WalletListAdapter == null)
{
//Fill the DataSource of the ListView with the Array of Names
WalletListAdapter = new WalletListAdapter(this, SortedWalletList);
GridviewWallet.Adapter = WalletListAdapter;
}
else
{
WalletListAdapter.refresh(SortedWalletList);
AgentInfoNeedsUpdate = true;
}
}
else
{
AgentInfoNeedsUpdate = false;
}
}
And in my WalletListAdapter I created the refresh function:
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
But the GridviewWallet never get's filled or doesn't get shown. What am I doing wrong?
EDIT:
Maybe there is something wrong in the WalletListAdapter, so here is the code of the class:
public class WalletListAdapter : BaseAdapter<wallet>
{
public List<wallet> mItems;
private Context mContext;
public WalletListAdapter(Context context, List<wallet> items)
{
mItems = items;
mContext = context;
}
public override int Count
{
get { return mItems.Count; }
}
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
public override long GetItemId(int position)
{
return position;
}
public override wallet this[int position]
{
get { return mItems[position]; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.walletlist_row, null, false);
var txtWalletCoin = row.FindViewById<TextView>(Resource.Id.txtWalletCoin);
var txtWalletQuantity = row.FindViewById<TextView>(Resource.Id.txtWalletQuantity);
var txtAvgPrice = row.FindViewById<TextView>(Resource.Id.txtWalletAvgPrice);
var txtWalletValue = row.FindViewById<TextView>(Resource.Id.txtWalletValue);
var txtProfitUSDT = row.FindViewById<TextView>(Resource.Id.txtWalletProfitUSDT);
var txtProfitPerc = row.FindViewById<TextView>(Resource.Id.txtWalletProfitPerc);
row.Tag = new WalletViewHolder()
{
txtWalletCoin = txtWalletCoin,
txtWalletQuantity = txtWalletQuantity,
txtAvgPrice = txtAvgPrice,
txtWalletValue = txtWalletValue,
txtProfitUSDT = txtProfitUSDT,
txtProfitPerc = txtProfitPerc
};
}
var holder = (WalletViewHolder)row.Tag;
holder.txtWalletCoin.Text = mItems[position].Coin;
holder.txtWalletQuantity.Text = Math.Round(mItems[position].Quantity, 2).ToString();
holder.txtAvgPrice.Text = Math.Round(mItems[position].AvgPrice, 2).ToString();
holder.txtWalletValue.Text = Math.Round(mItems[position].Value, 2).ToString();
if (mItems[position].Coin != "USDT")
{
holder.txtProfitUSDT.Text = Math.Round(mItems[position].ProfitUSDT, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(mItems[position].ProfitPerc, 1).ToString();
}
else
{
holder.txtProfitUSDT.Text = Math.Round(0.00, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(0.00, 1).ToString();
}
return row;
}
}
Hope this discussion provides some insights to fix the gridview refresh using Xamarin. According to it, the grid has to be recreated.
https://forums.xamarin.com/discussion/115256/refresh-a-gridview

Load Windows form after complete combobox data load in c#

I have a form for employees called frmEmployees where I need to load couple of combo box with data like country, category, nationality, such others.
Now when user click on to open frmEmployees, window is stuck for bit and then open. I assume that this is because of data loading and initializing the combo box.
Now! what I want is, just after click on button to open frmEmployees run a progress bar till data loading complete and then open form.
public frmEmployee()
{
InitializeComponent();
con = new Connection();
LoadComboboxDS();
}
I have tried also
private void FrmEmployee_Load(object sender, EventArgs e)
{
LoadComboboxDS();
}
private void LoadComboboxDS()
{
//company
var _companies = con.Companies.Where(x => x.IsDeleted == false).ToList();
_companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = _companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
//gender
cbGender.DataSource = Enum.GetValues(typeof(Gender));
//merital status
cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));
//citizenship
var _citizenships = con.Countries.Select(x => x.Citizenship).Distinct().ToList();
_citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
//nationality
var _nations = con.Countries.Select(x => x.Name).Distinct().ToList();
_nations.Insert(0, "--Select--");
cbNationality.DataSource = _nations;
cbNationality.DisplayMember = "Name";
//domicile
var _domiciles = con.Countries.Select(x => x.Name).Distinct().ToList();
_domiciles.Insert(0, "--Select--");
cbDomicile.DataSource = _domiciles;
cbDomicile.DisplayMember = "Name";
//cast category
var _casts = con.CastCategories.Select(x => new {x.ShortText, x.Description}).Distinct().ToList();
_casts.Insert(0, new { ShortText = "", Description = "--Select--" });
cbCategory.DataSource = _casts;
cbCategory.DisplayMember = "Description";
cbCategory.ValueMember = "ShortText";
//religion
cbReligion.DataSource = Enum.GetValues(typeof(Religion));
}
You can use Async extension methods of Entity Framework 6 to make your code asynchronous.
Separate your data access and presentation layer, at first:
public static class MyRepository // consider not static, just an example
{
public static async Task<List<Company>> GetCompanies()
{
using (var connection = new Connection()) // consider factory
{
return await con.Companies.Where(x => x.IsDeleted == false).ToListAsync();
}
}
public async Task<List<Citizenship>> GetCitizenships()
{
using (var connection = new Connection()) // factory?
{
return await con.Countries.Select(x => x.Citizenship).Distinct().ToList();
}
}
}
Then, you can run all these tasks at once and wait for them to complete:
// Wherever you are going to open frmEmployee
public async Task openFrmEmployee_OnClick(object sender, EventArgs e)
{
var getCompaniesTask = MyRepository.GetCompanies();
var getCitizenshipsTask = MyRepository.GetCitizenships();
await Task.WhenAll(getCompaniesTask, getCitizenshipsTask); // UI thread is not blocked
var form = new FrmEmployee(getCompaniesTask.Result, getCitizenshipsTask.Result); // form is created with data
}
Now, you only need to make your form accept complete data in constructor instead of making your form load this data which breaks abstraction:
public class FrmEmployees
{
public FrmEmployees(List<Company> companies, List<Citizenship> citizenships)
{
companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
// etc.
}
}
One important thing: you can get many tasks and many data passed to a form constructor. If all this data is going to be used often togetther, then you would probably want to encapsulate this "get all these things" logic into a single place to remove possible code duplication.
See what I have done... if anyone can review my code it would be appreciable.
public class EmployeeFormDataRepesenter
{
public List<Company> Companies { get; set; }
public List<Country> Countries { get; set; }
public List<CastCategory> CastCategories { get; set; }
}
public void LoadData(EmployeeFormDataRepesenter representer)
{
//gender
cbGender.DataSource = Enum.GetValues(typeof(Gender));
//merital status
cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));
//religion
cbReligion.DataSource = Enum.GetValues(typeof(Religion));
//company
var _companies = representer.Companies;
_companies.Insert(0, new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = _companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
//citizenship
var _citizenships = representer.Countries.Select(x => x.Citizenship).ToList();
_citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
//nationality
var _nations = representer.Countries.Select(x => x.Name).ToList();
_nations.Insert(0, "--Select--");
cbNationality.DataSource = _nations;
cbNationality.DisplayMember = "Name";
//domicile
var _domiciles = representer.Countries.Select(x => x.Name).ToList();
_domiciles.Insert(0, "--Select--");
cbDomicile.DataSource = _domiciles;
cbDomicile.DisplayMember = "Name";
//cast category
var _casts = representer.CastCategories.Select(x => new { x.ShortText, x.Description }).Distinct().ToList();
_casts.Insert(0, new { ShortText = "", Description = "--Select--" });
cbCategory.DataSource = _casts;
cbCategory.DisplayMember = "Description";
cbCategory.ValueMember = "ShortText";
}
private async void btnEmplyee_Click(object sender, EventArgs e)
{
con = new Connection();
Action showProgress = () => frmStatrup._progressBar.Visible = true;
Action hideProgress = () => frmStatrup._progressBar.Visible = false;
EmployeeFormDataRepesenter representer;
Task<List<Company>> _taskCompany = new Task<List<Company>>(() =>
{
BeginInvoke(showProgress);
var list = con.Companies.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
Task<List<Country>> _taskCountry = new Task<List<Country>>(() =>
{
BeginInvoke(showProgress);
var list = con.Countries.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
Task<List<CastCategory>> _taskCasts = new Task<List<CastCategory>>(() =>
{
BeginInvoke(showProgress);
var list = con.CastCategories.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
_taskCompany.Start();
var _companies = await _taskCompany;
_taskCountry.Start();
var _countries = await _taskCountry;
_taskCasts.Start();
var _casts = await _taskCasts;
if (_companies.Count != 0)
{
representer = new EmployeeFormDataRepesenter();
representer.Companies = _companies;
representer.Countries = _countries;
representer.CastCategories = _casts;
}
else
{
representer = null;
}
if (representer != null)
{
frmEmployee _emp = new frmEmployee();
_emp.LoadData(representer);
Functions.OpenForm(_emp, this.ParentForm);
}
}

DevExpress Lookupedit Set Selected Value

I have following Grid where it populates InquiryDetails in the Win Form Load event
private void frmInquiryManagement_Load(object sender, EventArgs e)
{
InquiryService inquiry = new InquiryService();
clearGetInquiry();
DataTable dt = InfoPCMS.db.executeSelectQuery("select * from Inquiry");
gridInquiryList.DataSource = dt;
DataTable dt2 = InfoPCMS.db.executeSelectQuery("select * from Customer");
txtCustomer.Properties.DataSource = dt2;
txtCustomer.Properties.ValueMember = "Id";
txtCustomer.Properties.DisplayMember = "CustomerName";
txtCustomer.Properties.NullText = "Please Select Customer";
txtCustomer.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CustomerName"));
txtCustomer.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Address"));
txtCustomer.Properties.ShowHeader = false;
int nextid = inquiry.getNextId();
txtInquiryNo.Text = nextid.ToString();
}
By double clicking on a row, it searches for all the details and displays in "Get Inquiries" Tab as follows, code of that is below the image
private void selectInquiry(object sender, EventArgs e)
{
btnAddInquiry.Enabled = false;
btnUpdate.Enabled = true;
txtInquiryNo.Enabled = false;
String inquiryno = gridView1.GetFocusedDataRow()["InquiryNumber"].ToString();
InquiryService inquiry = new InquiryService();
inquiry = inquiry.searchInquiry(inquiryno);
if (inquiry != null)
{
txtInquiryNo.Text = inquiry.InquiryNumber.ToString();
//txtDate.Text = inquiry.InquiryDate;
txtDate.Text = InfoPCMS.conversion.convertDate(inquiry.InquiryDate);
txtCustomer.EditValue = inquiry.CustomerID.ToString();
txtInquiryTaken.Text = inquiry.InquiryTaken;
txtInspectionDetails.Text = inquiry.InspectionDetails;
txtProblemNature.Text = inquiry.ProblemNature;
txtProblemSource.Text = inquiry.ProblemSource;
txtSiteResponsible.Text = inquiry.SiteResponsible;
txtQuotationNo.Text = inquiry.QuotationNumber.ToString();
txtFollowupDetails.Text = inquiry.FollowupDetails;
txtInspectionDone.Text = inquiry.InspectionDone;
tabInquiryManagement.SelectedTabPage = xtraTabPage2;
}
else
{
MessageBox.Show(InfoPCMS.message.GET_NO_SUCH_RECORD_INFORMATION(), "Information");
}
}
First time you search it works fine, But after when you clear all the fields and the page and try another record it will give all the records but the Lookupedit value to its null state as follows,
private void clearGetInquiry() {
txtInquiryNo.Text = "";
txtDate.Text = "";
txtCustomer.EditValue = null;
txtInquiryTaken.Text = "";
txtInspectionDetails.Text = "";
txtProblemNature.Text = "";
txtProblemSource.Text = "";
txtSiteResponsible.Text = "";
txtQuotationNo.Text = "";
txtFollowupDetails.Text = "";
txtInspectionDone.Text = "";
btnAddInquiry.Text = "Add Inquiry";
InquiryService inquiry = new InquiryService();
int nextid = inquiry.getNextId();
txtInquiryNo.Text = nextid.ToString();
tabInquiryManagement.SelectedTabPage = xtraTabPage1;
btnAddInquiry.Enabled = true;
btnUpdate.Enabled = false;
txtInquiryNo.Enabled = true;
}
How can I get rid of this issue? (This happens even when you do the search after going into the "Get Inquiries" Tab and come.

Cascading dropdown with Ajax

I am new to Ajax. I am implementing a cascading dropdown in a telerik RadGrid.
I am adding the dropdownList and CascadingDropDown as follows:
DropDownList droplist = new DropDownList();
droplist.ID = "DropDownListOrderTask";
droplist.AutoPostBack = true;
item["OrderTask"].Controls.Add(droplist);
CascadingDropDown ccdOrderTask = new CascadingDropDown();
ccdOrderTask.ID = "ccdOrderTask";
ccdOrderTask.Category = "OrderTask";
ccdOrderTask.TargetControlID = "DropDownListOrderTask";
ccdOrderTask.PromptText = "Select Order Task";
ccdOrderTask.LoadingText = "Loading OrderTask";
ccdOrderTask.ServiceMethod = "BindOrderTask";
ccdOrderTask.ServicePath = "ajaxservice.asmx";
TextBox txt = (TextBox)item["TaskOwner"].Controls[0];
txt.Visible = false;
droplist = new DropDownList();
droplist.ID = "DropDownListTaskOwner";
item["TaskOwner"].Controls.Add(droplist);
CascadingDropDown ccdTaskOwner = new CascadingDropDown();
ccdTaskOwner.ID = "ccdTaskOwner";
ccdTaskOwner.Category = "TaskOwner";
ccdTaskOwner.ParentControlID = "DropDownListOrderTask";
ccdTaskOwner.TargetControlID = "DropDownListTaskOwner";
ccdTaskOwner.PromptText = "Select Task Owner";
ccdTaskOwner.LoadingText = "Loading Task Owner";
ccdTaskOwner.ServiceMethod = "BindTaskOwner";
ccdTaskOwner.ServicePath = "ajaxservice.asmx";
On the PreRender I have the following:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
var ajaxManager = RadAjaxManager.GetCurrent(Page);
if(ajaxManager != null)
ajaxManager.AjaxSettings.AddAjaxSetting(this._UpdatePanel, this._RadGrid1, this._RadLoadingPanel);
}
In the ajaxservice.asmx I have the following:
[WebMethod]
public CascadingDropDownNameValue[] BindOrderTask(string knownCategoryValues, string category)
{
OrderRequestTaskTypeTable _orderRequestTaskTypeTable = new OrderRequestTaskType_List().ExecuteTypedDataTable();
List<CascadingDropDownNameValue> orderTaskDetails = new List<CascadingDropDownNameValue>();
foreach(DataRow dtRow in _orderRequestTaskTypeTable.Rows)
{
String orderTaskId = dtRow["OrderRequestTaskTypeId"].ToString();
String orderTaskName = dtRow["DescriptionTaskType"].ToString();
orderTaskDetails.Add(new CascadingDropDownNameValue(orderTaskId, orderTaskName));
}
return orderTaskDetails.ToArray();
}
The first dropDown, DropDownListOrderTask contains no values. On debugging through Firebug it says: ReferenceError: BindOrderTask is not defined
I am sure I am missing something but not sure what. Please help me.

how to set the navigationUrl of a hyperlinkField in SPGridView

I am trying to get all site-collections under the root site and display them using SPGridView. In the SPGridView I am using HyperlinkField to display the name, url and created for each site.
My problem is that I cannot attach the url of the site to HyperlinkField. Any idea how this can be done in code?
[ToolboxItemAttribute(false)]
public class SPGridViewDemo : WebPart
{
private SPGridView grid;
private ObjectDataSource gridDS;
public DataTable SelectData()
{
DataTable dataSource = new DataTable();
dataSource.Columns.Add("Name");
dataSource.Columns.Add("Created");
dataSource.Columns.Add("Url");
SPWebApplication webApplication = SPContext.Current.Site.WebApplication;
SPSiteCollection siteCollections = webApplication.Sites;
SPSite currentSite = SPContext.Current.Site;
foreach (SPSite siteCollection in siteCollections)
{
dataSource.Rows.Add(siteCollection.RootWeb.Title, siteCollection.RootWeb.Created, siteCollection.RootWeb.Url);
}
return dataSource;
}
protected sealed override void Render(HtmlTextWriter writer)
{
BoundField column = new BoundField();
HyperLinkField hyplink = new HyperLinkField();
hyplink.DataTextField = "Name";
hyplink.NavigateUrl = "Url";
hyplink.SortExpression = "Name";
hyplink.HeaderText = "Workspaces";
grid.Columns.Add(hyplink);
column = new BoundField();
column.DataField = "Created";
column.SortExpression = "Created";
column.HeaderText = "Created";
grid.Columns.Add(column);
column = new BoundField();
column.DataField = "Url";
column.SortExpression = "Url";
column.HeaderText = "Url";
grid.Columns.Add(column);
grid.Sort("Name",System.Web.UI.WebControls.SortDirection.Descending);
grid.DataBind();
base.Render(writer);
}
protected sealed override void CreateChildControls()
{
const string gridId = "grid";
const string dataSourceId = "gridDS";
gridDS = new ObjectDataSource();
gridDS.ID = dataSourceId;
gridDS.SelectMethod = "SelectData";
gridDS.TypeName = this.GetType().AssemblyQualifiedName;
gridDS.ObjectCreating += new ObjectDataSourceObjectEventHandler(gridDS_ObjectCreating);
this.Controls.Add(gridDS);
grid = new SPGridView();
grid.ID = gridId;
grid.DataSourceID = gridDS.ID;
grid.AutoGenerateColumns = false;
// Paging
grid.AllowPaging = true;
grid.PageSize = 5;
// Sorting
grid.AllowSorting = true;
this.Controls.Add(grid);
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = grid.ID;
this.Controls.Add(pager);
}
private void gridDS_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = this;
}
You should use the HyperLinkField.DataNavigateUrlFields Property instead:
HyperLinkField hyplink = new HyperLinkField();
hyplink.DataTextField = "Name";
hyplink.DataNavigateUrlFields = new string[] { "Url" };
hyplink.SortExpression = "Name";
hyplink.HeaderText = "Workspaces";
grid.Columns.Add(hyplink);
The HyperLinkField.NavigateUrl Property is used to render static urls:
Use the NavigateUrl property to specify the URL to navigate to when a hyperlink in a HyperLinkField object is clicked. When this property is set, each hyperlink shares the same navigation URL.

Categories