how to set the navigationUrl of a hyperlinkField in SPGridView - c#

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.

Related

How to add rows under multi-layered column headers added by StackedHeaderDecorator

I am working on C#. I use this code copied from the link below to show multi-layered column headers to DataGridView.
DataGridView – Stacked Header
I succeeded to show multi-layered col header itself, but I can't add rows under the column headers. Instead, I got the added rows to be appeared in the col headers that are automatically created besides the multi-layered column headers.
private void Form1_Load(object sender, EventArgs e)
{
DataGridView dgv = dataGridView_syukei;
StackedHeaderDecorator objREnderer = new StackedHeaderDecorator(dgv);
dgv.Columns.Add("Name", "a.Name");
dgv.Columns.Add("1", "a.Id");
List<TestClass> testClasses = new List<TestClass>();
TestClass testClass1 = new TestClass();
testClass1.Id = 1;
testClass1.Name = "John";
TestClass testClass2 = new TestClass();
testClass2.Id = 2;
testClass2.Name = "Mike";
testClasses.Add(testClass1);
testClasses.Add(testClass2);
dgv.DataSource = testClasses;
}
class TestClass
{
public string Name { get; set; }
public int Id { get; set; }
}
Adding AutoGenerateColumns = false and DataPropertyName soloved this problem.
private void Form1_Load(object sender, EventArgs e)
{
DataGridView dgv = dataGridView_syukei;
dgv.AutoGenerateColumns = false;
StackedHeaderDecorator objREnderer = new StackedHeaderDecorator(dgv);
DataGridViewColumn dataGridViewColumn_Name = new DataGridViewColumn();
dataGridViewColumn_Name.HeaderText = "a.Name";
dataGridViewColumn_Name.DataPropertyName = "Name";
dataGridViewColumn_Name.CellTemplate = new DataGridViewTextBoxCell();
dgv.Columns.Add(dataGridViewColumn_Name);
DataGridViewColumn dataGridViewColumn_Id = new DataGridViewColumn();
dataGridViewColumn_Id.HeaderText = "a.Id";
dataGridViewColumn_Id.DataPropertyName = "Id";
dataGridViewColumn_Id.CellTemplate = new DataGridViewTextBoxCell();
dgv.Columns.Add(dataGridViewColumn_Id);
List<TestClass> testClasses = new List<TestClass>();
TestClass testClass1 = new TestClass();
testClass1.Id = 1;
testClass1.Name = "John";
TestClass testClass2 = new TestClass();
testClass2.Id = 2;
testClass2.Name = "Mike";
testClasses.Add(testClass1);
testClasses.Add(testClass2);
dgv.DataSource = testClasses;
}

Cardview Columns using Devexpress

created a few seconds ago
Hi,
I am creating a web page in asp.net based on data from a database. This should result in a number of tab pages with card views on each tab with 5 columns and a maximum of 20 rows. The tab pages are working, the rows are working but the columns will not change from the default 3 columns.
I have tried setting the columnCount property at different stages, post and pre databinding. This getting frustrating.
I am having problems with setting a card views column count programmatically. I am setting it, have tried to set it in different places but it always goes to the default 3 columns :(
I am using C# in Visual studio 2017.
Here is the code I am using:
SqlDataSource sds = new SqlDataSource();
public string fName;
protected void Page_Load(object sender, EventArgs e)
{
string fid = Request.QueryString["FID"];
sds.ConnectionString = ConfigurationManager.ConnectionStrings["DataBaseConnection"].ToString();
sds.SelectCommand = "select name from [flashboard] where flashboardid = " + fid;
DataView fDet = (DataView)sds.Select(DataSourceSelectArguments.Empty);
fName = fDet.Table.Rows[0]["name"].ToString();
TitleLink.InnerHtml = fName;
sds.SelectCommand = "SELECT flashboardtabid, name FROM [FlashboardTab] WHERE flashboardid = " + fid+" order by SeqNo";
DataView fTab = (DataView)sds.Select(DataSourceSelectArguments.Empty);
TabPage tabDet;
ASPxPageControl tpc = ASPxPageControl1;
ASPxCardView cardGrp;
CardViewTextColumn cName;
CardViewHyperLinkColumn cEvidence;
foreach (DataRow tab in fTab.Table.Rows)
{
tabDet = new TabPage();
tabDet.Text = tab["name"].ToString();
tabDet.Name = "Tab"+tab["flashboardtabid"].ToString();
tabDet.ActiveTabStyle.Width = Unit.Percentage( 80);
cardGrp = new ASPxCardView();
cardGrp.ID = "CardGroup" + tab["flashboardtabid"].ToString() ;
tabDet.Controls.Add(cardGrp);
tpc.TabPages.Add(tabDet);
cardGrp.AutoGenerateColumns = false;
ASPxCardViewPagerSettings cvps = new ASPxCardViewPagerSettings(cardGrp);
cardGrp.EnableTheming = true;
cardGrp.Theme = "SoftOrange";
cvps.Visible = false;
cvps.SettingsTableLayout.ColumnCount = 5;
cvps.SettingsTableLayout.RowsPerPage = 20;
cardGrp.DataSource = GetData("SELECT cardid, Description, EvidencePage, SmartViewid FROM [flashboardcard] WHERE flashboardtabid = "+tab["flashboardtabid"] + " order by SeqNo");
cardGrp.Attributes.Add("Width", "80%");
cardGrp.Attributes.Add("style", "margin:auto");
cName = new CardViewTextColumn();
cName.Name = "Description";
cName.FieldName = "Description";
cEvidence = new CardViewHyperLinkColumn();
cEvidence.Name = "EvidencePage";
cEvidence.FieldName = "EvidencePage";
cEvidence.PropertiesHyperLinkEdit.Text = "Evidence";
cardGrp.Columns.Add(cName);
cardGrp.Columns.Add(cEvidence);
var layoutitem1 = new CardViewColumnLayoutItem(); // cardGrp.CardLayoutProperties.FindColumnItem("EvidencePage");
layoutitem1.ColumnName = "EvidencePage";
layoutitem1.ShowCaption = DevExpress.Utils.DefaultBoolean.False;
layoutitem1.HorizontalAlign = FormLayoutHorizontalAlign.Center;
var layoutitem2 = new CardViewColumnLayoutItem();
layoutitem2.ColumnName = "Description";
layoutitem2.ShowCaption = DevExpress.Utils.DefaultBoolean.False;
layoutitem2.HorizontalAlign = FormLayoutHorizontalAlign.Center;
layoutitem2.ParentContainerStyle.Font.Bold = true;
layoutitem2.ParentContainerStyle.Font.Size = FontUnit.Medium;
cardGrp.CardLayoutProperties.Items.Add(layoutitem2);
cardGrp.CardLayoutProperties.Items.Add(layoutitem1);
cardGrp.DataBind();
}
}
DataView GetData(String queryString)
{
DataView ds = new DataView();
sds.SelectCommand = queryString;
ds = (DataView)sds.Select(DataSourceSelectArguments.Empty);
return ds;
}
To resolve this issue with ColumnCount, I recommend you define it directly in the control's SettingsPager.SettingsTableLayout.ColumnCount property instead of specifying it in a new ASPxCardViewPagerSettings instance:
cardGrp.SettingsPager.SettingsTableLayout.ColumnCount = 5;
cardGrp.SettingsPager.SettingsTableLayout.RowsPerPage = 20;

Centering specific column in RadListView (Telerik, Winforms)

I'm using a (Telerik) RadListView (Telerik.WinControls.UI.RadListView()) in my project.
The listview has a few columns:
public MainForm()
{
Telerik.WinControls.UI.ListViewDetailColumn newColumn;
InitializeComponent();
newColumn = new ListViewDetailColumn("ID", "ID");
newColumn.Width = 250;
newColumn.Visible = false;
this.MyListView.Columns.Add(newColumn);
newColumn = new ListViewDetailColumn("Name", "Name");
newColumn.Width = 250;
newColumn.Visible = true;
this.MyListView.Columns.Add(newColumn);
newColumn = new ListViewDetailColumn("Description", "Description");
newColumn.Width = 250;
newColumn.Visible = true;
this.MyListView.Columns.Add(newColumn);
newColumn = new ListViewDetailColumn("Costs", "Costs");
newColumn.Width = 250;
newColumn.Visible = true;
this.MyListView.Columns.Add(newColumn);
I'm populating the listview manually by adding ListViewDataItems to it:
foreach (Data.Tablename listEntry in ListOfTableEntries)
{
ListViewDataItem newRow = new ListViewDataItem(listEntry.Id, new string[]{ listEntry.Name, listEntry.Description, listEntry.Costs});
this.MyListView.Items.Add(newRow);
}
So far so good. What I did not find out though is how I can format specific columns that are making up the added row. For example: Right-align the costs.
How can I do that (without also right-aligning all other columns)?
Thanks
Try something along these lines:
private void radListView1_CellFormatting(object sender, ListViewCellFormattingEventArgs e)
{
if ((e.CellElement).Data.HeaderText == "ID")
{
if ((e.CellElement is DetailListViewDataCellElement))
{
e.CellElement.TextAlignment = ContentAlignment.TopRight;
}
}
if ((e.CellElement).Data.HeaderText == "Name")
{
if ((e.CellElement is DetailListViewDataCellElement))
{
e.CellElement.TextAlignment = ContentAlignment.MiddleCenter;
}
//end so on
}
}

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.

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