Search Results

Search found 6151 results on 247 pages for 'controls'.

Page 5/247 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • VB.NET dynamic use of form controls

    - by Marcx
    I have 10 labels named lbl1, lbl2, ... lbl10 I'd like to change their propriety (using a cicle) with the cicle index for i as integer=1 to 10 step 1 lbl (i) = PROPRETY 'I know this is wrong but it's what I would do... end for I'm using a workaround, but I'm looking for a better way.. Dim exm(10) As Label exm(1)=lbl1 exm(2)=lbl2 ... exm(10)=lbl10 for i as integer=1 to 10 step 1 exm (i) = PROPRETY end for

    Read the article

  • How to use a viewstate'd object as a datasource for controls on a user control

    - by user557325
    I've got a listview on a control. Each row comprises a checkbox and another listview. The outer listview is bound to a property on the control (via a method call, can't set a property as a SelectMethod on an ObjectDataSource it would appear) which is lazy loaded suchly: Public ReadOnly Property ProductLineChargeDetails() As List(Of WebServiceProductLineChargeDetail) Get If ViewState("WSProductLineChargeDetails") Is Nothing Then ViewState("WSProductLineChargeDetails") = GetWebServiceProductLineChargeDetails() End If Return DirectCast(ViewState("WSProductLineChargeDetails"), Global.System.Collections.Generic.List(Of Global.MI.Open.WebServiceProductLineChargeDetail)) End Get End Property The shape of the object referenced by the data source is something like this: (psuedocode) Product { bool Licenced; List<Charge> charges; } Charge { int property1; string property2; bool property3 . . . } The reason for the use of viewstate is this: When an one of the checkboxes on one of the outer list view rows is checked or unchecked I want to modify the object that the ODS represents (for example I'll add a couple of Charge objects to the relevant Product object) and then rebind. The problem I'm getting is that after every postback (specifically after checking or unchecking one of the rows' checkbox) my viewstate is empty. Thiss means that any changes I make to my viewstate'd object is lost. Now, I've worked out (after much googling and reading, amongst many others, Scott Mitchel's excellent bit on ViewState) that during initial databinding IsTrackingViewState is set to false. That means, I think, that assigning the return from GetWebServiceProductLineChargeDetails() to the ViewState item in my Property Get during the initial databind won't work. Mind you, even when the IsTrackingViewState is true and I call the Property Get, come the next postback, the viewstate is empty. So do you chaps have any ideas on how I keep the object referenced by the ObjectDataSource in ViewState between postbacks and update it and get those changes to stay in ViewState? This has been going on for a couple of days now and I'm getting fed up! Cheers in advance Steve

    Read the article

  • How to include other controls in a scrollbar?

    - by Paperflyer
    I want to create a scrollview with a zooming control and a button next to the scrollbar. Sort of like the "tile window" button in XCode (top right corner of the editor), it should be in the same box that usually is used by the scrollbar only. Do you have an idea of how to approach this? I was thinking to use an NSScrollView and set the scrollbars to a custom subclass of NSScroller which includes the other widgets. What kinds of buttons use the same style as the scrollbar?

    Read the article

  • Prevent deferred creation of controls.

    - by Scott Chamberlain
    Here is a test framework to show what I am doing, just create a new project add a tabbed control, on tab 1 put a button on tab 2 put a check box (default names) and paste this code for its code public partial class Form1 : Form { private List<bool> boolList = new List<bool>(); BindingSource bs = new BindingSource(); public Form1() { InitializeComponent(); boolList.Add(false); bs.DataSource = boolList; checkBox1.DataBindings.Add("Checked", bs, ""); } bool updating = false; private void button1_Click(object sender, EventArgs e) { updating = true; boolList[0] = true; bs.ResetBindings(false); Application.DoEvents(); updating = false; } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (!updating) MessageBox.Show("CheckChanged fired outside of updating"); } } The issue is if you run the program and look at tab 2 then press the button on tab 1 the program works as expected, however if you press the button on tab 1 then look at tab 2 the event for the checkbox will not fire untill you look at tab 2. The reason for this is the controll on tab 2 is not in the "created" state, so its binding to change the checkbox from unchecked to checked does not happen until after the control has been "Created". checkbox1.CreateControl() does not do anything because according to MSDN CreateControl does not create a control handle if the control's Visible property is false. You can either call the CreateHandle method or access the Handle property to create the control's handle regardless of the control's visibility, but in this case, no window handles are created for the control's children. I tried getting the value of Handle(there is no CreateHandle for Button) but still the same result. Any suggestions other than have the program quickly flash all of my tabs that have data-bound check boxes when it first loads?

    Read the article

  • sharing web user controls across projects.

    - by Kyle
    I've done this using a regular .cs file that just extends System.Web.UI.UserControl and then included the assembly of the project that contains the control into other projects. I've also created .ascx files in one project then copied all ascx files from a specified folder in the properties-Build Events-Pre-build event. Now what I want to do is a combination of those two: I want to be able to use ascx files that I build in one project, in all of my other projects but I want to include them just using assembly references rather than having to copy them to my "secondary" projects as that seems a ghetto way to accomplish what I want to do. It works yes, but it's not very elegant. Can anyone let me know if this even possible, and if so, what the best way to approach this is?

    Read the article

  • Create Personalized Controls For Java ME

    - by Nathan Campos
    I'm starting to develop a eBook reader for mobile using Java ME, but for the control were the book will be shown I need a personalized control. For this I need to first know how to do one, to workaround with my needs. Then I need to know how can I do a personalized control as we do with Visual Basic. PS: I want to do a personalized TextBox, that in some parts can be in bold, italic, sublined, that supports topics(as the Edit, the MS-DOS Text Editor) and many other things that make a eBook better viewed than a simple plain text

    Read the article

  • How to set margin for inner controls of WrapPanel

    - by Andrey Tagaew
    Hi Guys! I'm new in WPF and have a question. Here is an example that I'm using: <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel> <WrapPanel Orientation="Horizontal" > <Button Content="test1" Margin="10,0" Padding="10,10" /> <Button Content="test2" Margin="10,0" Padding="10,10" /> <Button Content="test3" Margin="10,0" Padding="10,10" /> <Button Content="test4" Margin="10,0" Padding="10,10" /> <Button Content="test5" Margin="10,0" Padding="10,10" /> </WrapPanel> </StackPanel> As you can see, my wrap panel has several buttons. Each button has the same margin and padding. The question is, is there a way of setting margin and padding for wrap panel, so each element inside the wrap panel may use it values? This make the code shorter and let me specify Margin and Padding only one time instead of setting it for each control in the panel. Thank you!

    Read the article

  • Events on controls in web server control

    - by MarkyMarc
    Hi All, I'm creating a web server control that has an image button on it. The html for the control is done in the RenderControls of the code, the control devrives from WebControl, IScriptControl, INamingContainer. The button is coded as follow in the RenderControls: System.Web.UI.WebControls.ImageButton img = new System.Web.UI.WebControls.ImageButton(); img.ImageUrl = "Url of the image"; img.Click += new ImageClickEventHandler(img_Click); img.ID = this.ClientID + "_img"; img.CausesValidation = false; imgLock.RenderControl(output); The button apreas in the browser but when i click on it, the page postsback but the event handler for the button doesn't get fired, from what i can figure out, since the control goes throught RenderControls eachtime the page is posted back, the button gets redrawn and the event handling disapears. This server control is in a master page. Anyone can help me on this? Thanks

    Read the article

  • How does .NET repaint controls?

    - by serhio
    Say I have a custom Label that I paint in my way. As lite example we have the code: Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs) ' MyBase.OnPaint(e) DO NOT USE ' Dim f As Font = Me.Font Dim g As Graphics = e.Graphics Dim textRect As Rectangle = New Rectangle(Me.Location, Me.Size) Using br As New SolidBrush(Me._TextColor) g.DrawString(_Text, f, br, textRect) End Using End Sub maybe this example is useless, because does not bring different behavior that a simple label, but it just for example. Now, the problem is that if this label moves the ancient label area will not be updated, and the old text will remain until the parent will be invalidated. So the question is: How to invalidate the former control region?

    Read the article

  • Creating controls in ASP with dynamic IDs

    - by mattdell
    Hi, I'm creating a chat widget that will be dropped into CommunityServer. The widget works great, but I just discovered that if I drop two of these widgets onto the same page, only one of them works! And I'm quite certain the reason is because the chat window is defined in ASP, and now there are two instances of the chat window, with the same ID, on the same page. I am doing this with straight ASP & Javascript (not by choice), so my chat window is defined as: <telerik:RadListBox ID="rlbMessages" runat="server" > (don't mind that it's a telerik control). So I was hoping I could do something like this: <telerik:RadListBox ID="<%= 'rlbMessages' + chatRoomID %>" runat="server" > But from what I've gathered, apparently you can't assign ID's this way? What is the alternative?

    Read the article

  • Inheriting System.Windows.Controls.Panel

    - by modosansreves
    I use the Panel to provide custom layout of UIElements. For this, I override MeasureOverride and ArrangeOverride. In ArrangeOverride proper locations are given to Children. In my application, there is a bunch of rather heavy (by number of visuals) children inside the panel, but only 2 of them are located inside the visible region at a time. Working with my application I feel like all the visuals are drown. I need to introduce a kind of 'virtualization' and make the children render (or take CPU cycles) selectively. How do I?

    Read the article

  • Detect changes to user input controls in Silverlight?

    - by code
    I have a childwindow with a number of Textboxes, Comboboxes, and DatePickers. I want to know if a user has changed any value in these (to know if I need to save to db) One way I could think of doing this are in the 'on chg' event handlers and set bool. But if a user changes the value, in say a combobox, then changes back to the original this would still be seen as a change. Are there other alternatives? (note the project is not set up as MVVM) Thanks

    Read the article

  • Dragging Controls on Form at runtime

    - by j-t-s
    Hi All I've just started using WPF. But I'm trying to add my code that (from Winforms) enables the user to drag any control whereever they wish at runtime. But I can't seem to get the current Location of the mouse... Eh? There is no Location for Mouse? :(

    Read the article

  • How do I get my custom WPF textbox to fill correctly?

    - by Dan Ryan
    I am trying to create a custom WPF textbox control that extends the standard textbox control but the extended textbox behaves differently when placed in control containers. Within my Window I have a stackpanel with a standard textbox and my extended textbox: <StackPanel Margin="10"> <TextBox Height="21" /> <l:SearchTextBox Search="SearchTextBox_Search" Height="21" Margin="0, 10, 0, 0" SearchMode="Delayed" HorizontalAlignment="Left" /> </StackPanel> The standard textbox stretches the length of the StackPanel whereas the custom textbox does not. How can I get the controls to behave the same? The styling for the custom textbox is shown below: <Style x:Key="{x:Type UIControls:SearchTextBox}" BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type UIControls:SearchTextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type UIControls:SearchTextBox}"> <TextBox /> </ControlTemplate> </Setter.Value> </Setter> </Style>

    Read the article

  • Panel in Windows Forms Application not clearing

    - by SwiftStriker00
    I'm working on my project: [Beer Pong Management System][1], a Windows Forms application. I am currently trying to add a whole tournament mode to it. In a nutshell, I've created a TabControl, with the first tab page with the settings and setup and the second page the brackets. There is a feature for each of the match-ups, that once there is a winner is decided, a yellow cancel button will appear in order to revert the tournament. However my issue is when i click the button the next match-up does not get removed in the series is going. See below: Image Here(not high enough rep to insert image) I have tried to set the MatchUp to null, I've tried dispose(), close(). even Parent.Controls.Remove(). Even after I switch tabs which is supposed to clear all, they still sit there when i come back. I have a feeling I might be loosing a reference or something because I can't even push new teams into them, they just sit there with their buttons. Does anyone have any tips or know of any known issues that might be causing this? Thanks. [1] _http://www.cs.rit.edu/~rmb1201/pages/code.shtml

    Read the article

  • Win a set of Infragistics Silverlight Controls with Data Visualization!

    - by mbcrump
    Infragistics recently released their new Silverlight Data Visualization Controls. I saw a couple of samples and had to take a look. I headed over to their website and downloaded the controls. I first noticed the hospital floor-plan demo shown on their site and started thinking of ways that I could use this in my own organization. I emailed them asking if I could give away the Silverlight Data Visualization controls on my site and they said, Yes! They also wanted to throw in the standard Silverlight Line of Business controls. (combined they are worth about $3000 US). I am very thankful they were willing to help the Silverlight community with this giveaway. So some quick rules below: ----------------------------------------------------------------------------------------------------------------------------------------------------------- Win a FREE developer’s license of Infragistics Silverlight Controls with Data Visualization ($3000 Value) Random winner will be announced on January 1st, 2011! To be entered into the contest do the following things: Subscribe to my feed. Leave a comment below with a valid email account (I WILL NOT share this info with anyone.) For extra entries simply: Retweet a link to this page using the following URL [ http://mcrump.me/iscfree ]. It does not matter what the tweet says, just as long as the URL is the same. Unlimited tweets, but please don’t go crazy! This URL will allow me to track the users that Tweet this page. Don’t forget to visit Infragistics because they made this possible. ---------------------------------------------------------------------------------------------------------------------------------------------------------- Before we get started with the Silverlight Controls, here is a couple of links to bookmark: The Silverlight Line of Business Control page is here. You can also check out the live demos here. The Data Visualization page is here. You can also check out the live demos here. Don’t worry about the Samples/Help Documentation. You can install all of that to your local HDD when you are installing it. I am going to walk you through the Silverlight Controls recently released by Infragistics. Begin by downloading the trial version and running the executable. If you downloaded the Complete bundle then you will have the following options to pick from. I like having help documentation and samples on my local HDD in case I do not have access to the internet and want to code. After it is installed, you may want to take a look at your Toolbox in Visual Studio 2010. Look for NetAdvantage 10.3 Silverlight and you will see that you now have access to all of these controls. At this point, to use the controls it’s as simple as drag/drop onto your Silverlight container. It will create the proper Namespaces for you. I wanted to highlight a few of the controls that I liked the most: Grid – After using the Infragistics grid you will wonder how you ever survived using the grid supplied by Microsoft standard controls.  This grid was designed to get your application up and running very fast. It’s simple to bind, it handles LARGE DataSets, easy to filter and allows endless possibilities of formatting data. The screenshot below is an example of the grid. For a real-time updating demo click here. SpellChecker- If your users are creating emails or performing any other function that requires Spell Checking then this control is great. Check out the screenshots below: In this first screen, I have a word that is not in the dictionary [DotNet]. The Spell Checker finds the word and allows the user to correct it. What is so great about Infragistics controls is that it only takes a few lines of code to have a full-featured Spell Checker in your application. TagCloud – This is a control that I haven’t seen anywhere else. It allows you to create keywords for popular search terms. This is very similar to TagCloud seen all over the internet.  Below is a screenshot that shows “Facebook” being a very popular item in the cloud. You can link these items to a hyperlink if you wanted. Importing/Exporting from Excel – I work with data a majority of the time. We all know the importance of Excel in our organizations, its used a lot. With Infragistics controls it make importing and exporting data from a Grid into Excel a snap. One of the things that I liked most about this control was the option to choose the Excel format (2003 or 2007). I haven’t seen this feature in other controls. Creating/Saving/Extracting/Uploading Zip Files – This is another control that I haven’t seen many others making. It allows you to basically manipulate a zip file in any way you like. You can even create a password on the zip file. Schedule – The Schedule that Infragistics provides resembles Outlook’s calendar. I think that it’s important for a user to see your app for the first time and immediately be able to start using because they are already familiar with the UI. The Schedule control accomplishes that in my opinion. I have just barely scratched the surface with the Infragistics Silverlight Line of Business controls. To check all of them then click here. A quick thing to note is that this giveaway also comes with the following Silverlight Data Visualization Controls. Below is a screenshot that list all of them:   I wanted to highlight 2 of the controls that I liked the most: xamBarcode– The xamBarcode supports the following Symbologies: Below is an example of the barcode generated by Infragistics controls. This is a high resolution barcode that you will not have to wonder if your scanner can read it. As long as you have ink in your printer your barcode will read it. I used a Symbol barcode reader to test this barcode. xamTreemap– I’ve never seen a way of displaying data like this before, but I like it. You can style this anyway that you like of course and it also comes with an Office 2010 Theme. Thanks to Infragistics for providing the controls to one lucky reader. I hope that you enjoyed this post and good luck to those that entered the contest.  Subscribe to my feed

    Read the article

  • Membership in ASP.Net applications - part 3

    - by nikolaosk
    This is the third post in a series of posts regarding ASP.Net built in membership functionality,providers,controls. You can read the first one post one here . You can read the second post here . In this post I would like to investigate how to use the Membership class methods to achieve the same functionality we have with the login web server controls.The login web server controls live inside the .aspx pages and access the underlying abstract membership classes to perform the desired functionality...(read more)

    Read the article

  • How to create Custom ListForm WebPart

    - by DipeshBhanani
    Mostly all who works extensively on SharePoint (including meJ) don’t like to use out-of-box list forms (DispForm.aspx, EditForm.aspx, NewForm.aspx) as interface. Actually these OOB list forms bind hands of developers for the customization. It gives headache to developers to add just one post back event, for a dropdown field and to populate other fields in NewForm.aspx or EditForm.aspx. On top of that clients always ask such stuff. So here I am going to give you guys a flight for SharePoint Customization world. In this blog, I will explain, how to create CustomListForm WebPart. In my next blogs, I am going to explain easy deployment of List Forms through features and last, guidance on using SharePoint web controls. 1.       First thing, create a class library project through Visual Studio and inherit the class with WebPart class.     public class CustomListForm : WebPart   2.       Declare the public variables and properties which we are going to use throughout the class. You will get to know these once you see them in use.         #region "Variable Declaration"           Table spTableCntl;         FormToolBar formToolBar;         Literal ltAlertMessage;         Guid SiteId;         Guid ListId;         int ItemId;         string ListName;           #endregion           #region "Properties"           SPControlMode _ControlMode = SPControlMode.New;         [Personalizable(PersonalizationScope.Shared),          WebBrowsable(true),          WebDisplayName("Control Mode"),          WebDescription("Set Control Mode"),          DefaultValue(""),          Category("Miscellaneous")]         public SPControlMode ControlMode         {             get { return _ControlMode; }             set { _ControlMode = value; }         }           #endregion     The property “ControlMode” is used to identify the mode of the List Form. The property is of type SPControlMode which is an enum type with values (Display, Edit, New and Invalid). When we will add this WebPart to DispForm.aspx, EditForm.aspx and NewForm.aspx, we will set the WebPart property “ControlMode” to Display, Edit and New respectively.     3.       Now, we need to override the CreateChildControl method and write code to manually add SharePoint Web Controls related to each list fields as well as ToolBar controls.         protected override void CreateChildControls()         {             base.CreateChildControls();               try             {                 SiteId = SPContext.Current.Site.ID;                 ListId = SPContext.Current.ListId;                 ListName = SPContext.Current.List.Title;                   if (_ControlMode == SPControlMode.Display || _ControlMode == SPControlMode.Edit)                     ItemId = SPContext.Current.ItemId;                   SPSecurity.RunWithElevatedPrivileges(delegate()                 {                     using (SPSite site = new SPSite(SiteId))                     {                         //creating a new SPSite with credentials of System Account                         using (SPWeb web = site.OpenWeb())                         {                               //<Custom Code for creating form controls>                         }                     }                 });             }             catch (Exception ex)             {                 ShowError(ex, "CreateChildControls");             }         }   Here we are assuming that we are developing this WebPart to plug into List Forms. Hence we will get the List Id and List Name from the current context. We can have Item Id only in case of Display and Edit Mode. We are putting our code into “RunWithElevatedPrivileges” to elevate privileges to System Account. Now, let’s get deep down into the main code and expand “//<Custom Code for creating form controls>”. Before initiating any SharePoint control, we need to set context of SharePoint web controls explicitly so that it will be instantiated with elevated System Account user. Following line does the job.     //To create SharePoint controls with new web object and System Account credentials     SPControl.SetContextWeb(Context, web);   First thing, let’s add main table as container for all controls.     //Table to render webpart     Table spTableMain = new Table();     spTableMain.CellPadding = 0;     spTableMain.CellSpacing = 0;     spTableMain.Width = new Unit(100, UnitType.Percentage);     this.Controls.Add(spTableMain);   Now we need to add Top toolbar with Save and Cancel button at top as you see in the below screen shot.       // Add Row and Cell for Top ToolBar     TableRow spRowTopToolBar = new TableRow();     spTableMain.Rows.Add(spRowTopToolBar);     TableCell spCellTopToolBar = new TableCell();     spRowTopToolBar.Cells.Add(spCellTopToolBar);     spCellTopToolBar.Width = new Unit(100, UnitType.Percentage);         ToolBar toolBarTop = (ToolBar)Page.LoadControl("/_controltemplates/ToolBar.ascx");     toolBarTop.CssClass = "ms-formtoolbar";     toolBarTop.ID = "toolBarTbltop";     toolBarTop.RightButtons.SeparatorHtml = "<td class=ms-separator> </td>";       if (_ControlMode != SPControlMode.Display)     {         SaveButton btnSave = new SaveButton();         btnSave.ControlMode = _ControlMode;         btnSave.ListId = ListId;           if (_ControlMode == SPControlMode.New)             btnSave.RenderContext = SPContext.GetContext(web);         else         {             btnSave.RenderContext = SPContext.GetContext(this.Context, ItemId, ListId, web);             btnSave.ItemContext = SPContext.GetContext(this.Context, ItemId, ListId, web);             btnSave.ItemId = ItemId;         }         toolBarTop.RightButtons.Controls.Add(btnSave);     }       GoBackButton goBackButtonTop = new GoBackButton();     toolBarTop.RightButtons.Controls.Add(goBackButtonTop);     goBackButtonTop.ControlMode = SPControlMode.Display;       spCellTopToolBar.Controls.Add(toolBarTop);   Here we have use “SaveButton” and “GoBackButton” which are internal SharePoint web controls for save and cancel functionality. I have set some of the properties of Save Button with if-else condition because we will not have Item Id in case of New Mode. Item Id property is used to identify which SharePoint List Item need to be saved. Now, add Form Toolbar to the page which contains “Attach File”, “Delete Item” etc buttons.       // Add Row and Cell for FormToolBar     TableRow spRowFormToolBar = new TableRow();     spTableMain.Rows.Add(spRowFormToolBar);     TableCell spCellFormToolBar = new TableCell();     spRowFormToolBar.Cells.Add(spCellFormToolBar);     spCellFormToolBar.Width = new Unit(100, UnitType.Percentage);       FormToolBar formToolBar = new FormToolBar();     formToolBar.ID = "formToolBar";     formToolBar.ListId = ListId;     if (_ControlMode == SPControlMode.New)         formToolBar.RenderContext = SPContext.GetContext(web);     else     {         formToolBar.RenderContext = SPContext.GetContext(this.Context, ItemId, ListId, web);         formToolBar.ItemContext = SPContext.GetContext(this.Context, ItemId, ListId, web);         formToolBar.ItemId = ItemId;     }     formToolBar.ControlMode = _ControlMode;     formToolBar.EnableViewState = true;       spCellFormToolBar.Controls.Add(formToolBar);     The ControlMode property will take care of which button to be displayed on the toolbar. E.g. “Attach files”, “Delete Item” in new/edit forms and “New Item”, “Edit Item”, “Delete Item”, “Manage Permissions” etc in display forms. Now add main section which contains form field controls.     //Create Form Field controls and add them in Table "spCellCntl"     CreateFieldControls(web);     //Add public variable "spCellCntl" containing all form controls to the page     spRowCntl.Cells.Add(spCellCntl);     spCellCntl.Width = new Unit(100, UnitType.Percentage);     spCellCntl.Controls.Add(spTableCntl);       //Add a Blank Row with height of 5px to render space between ToolBar table and Control table     TableRow spRowLine1 = new TableRow();     spTableMain.Rows.Add(spRowLine1);     TableCell spCellLine1 = new TableCell();     spRowLine1.Cells.Add(spCellLine1);     spCellLine1.Height = new Unit(5, UnitType.Pixel);     spCellLine1.Controls.Add(new LiteralControl("<IMG SRC='/_layouts/images/blank.gif' width=1 height=1 alt=''>"));       //Add Row and Cell for Form Controls Section     TableRow spRowCntl = new TableRow();     spTableMain.Rows.Add(spRowCntl);     TableCell spCellCntl = new TableCell();       //Create Form Field controls and add them in Table "spCellCntl"     CreateFieldControls(web);     //Add public variable "spCellCntl" containing all form controls to the page     spRowCntl.Cells.Add(spCellCntl);     spCellCntl.Width = new Unit(100, UnitType.Percentage);     spCellCntl.Controls.Add(spTableCntl);       TableRow spRowLine2 = new TableRow();     spTableMain.Rows.Add(spRowLine2);     TableCell spCellLine2 = new TableCell();     spRowLine2.Cells.Add(spCellLine2);     spCellLine2.CssClass = "ms-formline";     spCellLine2.Controls.Add(new LiteralControl("<IMG SRC='/_layouts/images/blank.gif' width=1 height=1 alt=''>"));       // Add Blank row with height of 5 pixel     TableRow spRowLine3 = new TableRow();     spTableMain.Rows.Add(spRowLine3);     TableCell spCellLine3 = new TableCell();     spRowLine3.Cells.Add(spCellLine3);     spCellLine3.Height = new Unit(5, UnitType.Pixel);     spCellLine3.Controls.Add(new LiteralControl("<IMG SRC='/_layouts/images/blank.gif' width=1 height=1 alt=''>"));   You can add bottom toolbar also to get same look and feel as OOB forms. I am not adding here as the blog will be much lengthy. At last, you need to write following lines to allow unsafe updates for Save and Delete button.     // Allow unsafe update on web for save button and delete button     if (this.Page.IsPostBack && this.Page.Request["__EventTarget"] != null         && (this.Page.Request["__EventTarget"].Contains("IOSaveItem")         || this.Page.Request["__EventTarget"].Contains("IODeleteItem")))     {         SPContext.Current.Web.AllowUnsafeUpdates = true;     }   So that’s all. We have finished writing Custom Code for adding field control. But something most important is skipped. In above code, I have called function “CreateFieldControls(web);” to add SharePoint field controls to the page. Let’s see the implementation of the function:     private void CreateFieldControls(SPWeb pWeb)     {         SPList listMain = pWeb.Lists[ListId];         SPFieldCollection fields = listMain.Fields;           //Main Table to render all fields         spTableCntl = new Table();         spTableCntl.BorderWidth = new Unit(0);         spTableCntl.CellPadding = 0;         spTableCntl.CellSpacing = 0;         spTableCntl.Width = new Unit(100, UnitType.Percentage);         spTableCntl.CssClass = "ms-formtable";           SPContext controlContext = SPContext.GetContext(this.Context, ItemId, ListId, pWeb);           foreach (SPField listField in fields)         {             string fieldDisplayName = listField.Title;             string fieldInternalName = listField.InternalName;               //Skip if the field is system field or hidden             if (listField.Hidden || listField.ShowInVersionHistory == false)                 continue;               //Skip if the control mode is display and field is read-only             if (_ControlMode != SPControlMode.Display && listField.ReadOnlyField == true)                 continue;               FieldLabel fieldLabel = new FieldLabel();             fieldLabel.FieldName = listField.InternalName;             fieldLabel.ListId = ListId;               BaseFieldControl fieldControl = listField.FieldRenderingControl;             fieldControl.ListId = ListId;             //Assign unique id using Field Internal Name             fieldControl.ID = string.Format("Field_{0}", fieldInternalName);             fieldControl.EnableViewState = true;               //Assign control mode             fieldLabel.ControlMode = _ControlMode;             fieldControl.ControlMode = _ControlMode;             switch (_ControlMode)             {                 case SPControlMode.New:                     fieldLabel.RenderContext = SPContext.GetContext(pWeb);                     fieldControl.RenderContext = SPContext.GetContext(pWeb);                     break;                 case SPControlMode.Edit:                 case SPControlMode.Display:                     fieldLabel.RenderContext = controlContext;                     fieldLabel.ItemContext = controlContext;                     fieldLabel.ItemId = ItemId;                       fieldControl.RenderContext = controlContext;                     fieldControl.ItemContext = controlContext;                     fieldControl.ItemId = ItemId;                     break;             }               //Add row to display a field row             TableRow spCntlRow = new TableRow();             spTableCntl.Rows.Add(spCntlRow);               //Add the cells for containing field lable and control             TableCell spCellLabel = new TableCell();             spCellLabel.Width = new Unit(30, UnitType.Percentage);             spCellLabel.CssClass = "ms-formlabel";             spCntlRow.Cells.Add(spCellLabel);             TableCell spCellControl = new TableCell();             spCellControl.Width = new Unit(70, UnitType.Percentage);             spCellControl.CssClass = "ms-formbody";             spCntlRow.Cells.Add(spCellControl);               //Add the control to the table cells             spCellLabel.Controls.Add(fieldLabel);             spCellControl.Controls.Add(fieldControl);               //Add description if there is any in case of New and Edit Mode             if (_ControlMode != SPControlMode.Display && listField.Description != string.Empty)             {                 FieldDescription fieldDesc = new FieldDescription();                 fieldDesc.FieldName = fieldInternalName;                 fieldDesc.ListId = ListId;                 spCellControl.Controls.Add(fieldDesc);             }               //Disable Name(Title) in Edit Mode             if (_ControlMode == SPControlMode.Edit && fieldDisplayName == "Name")             {                 TextBox txtTitlefield = (TextBox)fieldControl.Controls[0].FindControl("TextField");                 txtTitlefield.Enabled = false;             }         }         fields = null;     }   First of all, I have declared List object and got list fields in field collection object called “fields”. Then I have added a table for the container of all controls and assign CSS class as "ms-formtable" so that it gives consistent look and feel of SharePoint. Now it’s time to navigate through all fields and add them if required. Here we don’t need to add hidden or system fields. We also don’t want to display read-only fields in new and edit forms. Following lines does this job.             //Skip if the field is system field or hidden             if (listField.Hidden || listField.ShowInVersionHistory == false)                 continue;               //Skip if the control mode is display and field is read-only             if (_ControlMode != SPControlMode.Display && listField.ReadOnlyField == true)                 continue;   Let’s move to the next line of code.             FieldLabel fieldLabel = new FieldLabel();             fieldLabel.FieldName = listField.InternalName;             fieldLabel.ListId = ListId;               BaseFieldControl fieldControl = listField.FieldRenderingControl;             fieldControl.ListId = ListId;             //Assign unique id using Field Internal Name             fieldControl.ID = string.Format("Field_{0}", fieldInternalName);             fieldControl.EnableViewState = true;               //Assign control mode             fieldLabel.ControlMode = _ControlMode;             fieldControl.ControlMode = _ControlMode;   We have used “FieldLabel” control for displaying field title. The advantage of using Field Label is, SharePoint automatically adds red star besides field label to identify it as mandatory field if there is any. Here is most important part to understand. The “BaseFieldControl”. It will render the respective web controls according to type of the field. For example, if it’s single line of text, then Textbox, if it’s look up then it renders dropdown. Additionally, the “ControlMode” property tells compiler that which mode (display/edit/new) controls need to be rendered with. In display mode, it will render label with field value. In edit mode, it will render respective control with item value and in new mode it will render respective control with empty value. Please note that, it’s not always the case when dropdown field will be rendered for Lookup field or Choice field. You need to understand which controls are rendered for which list fields. I am planning to write a separate blog which I hope to publish it very soon. Moreover, we also need to assign list field specific properties like List Id, Field Name etc to identify which SharePoint List field is attached with the control.             switch (_ControlMode)             {                 case SPControlMode.New:                     fieldLabel.RenderContext = SPContext.GetContext(pWeb);                     fieldControl.RenderContext = SPContext.GetContext(pWeb);                     break;                 case SPControlMode.Edit:                 case SPControlMode.Display:                     fieldLabel.RenderContext = controlContext;                     fieldLabel.ItemContext = controlContext;                     fieldLabel.ItemId = ItemId;                       fieldControl.RenderContext = controlContext;                     fieldControl.ItemContext = controlContext;                     fieldControl.ItemId = ItemId;                     break;             }   Here, I have separate code for new mode and Edit/Display mode because we will not have Item Id to assign in New Mode. We also need to set CSS class for cell containing Label and Controls so that those controls get rendered with SharePoint theme.             spCellLabel.CssClass = "ms-formlabel";             spCellControl.CssClass = "ms-formbody";   “FieldDescription” control is used to add field description if there is any.    Now it’s time to add some more customization,               //Disable Name(Title) in Edit Mode             if (_ControlMode == SPControlMode.Edit && fieldDisplayName == "Name")             {                 TextBox txtTitlefield = (TextBox)fieldControl.Controls[0].FindControl("TextField");                 txtTitlefield.Enabled = false;             }   The above code will disable the title field in edit mode. You can add more code here to achieve more customization according to your requirement. Some of the examples are as follow:             //Adding post back event on UserField to auto populate some other dependent field             //in new mode and disable it in edit mode             if (_ControlMode != SPControlMode.Display && fieldDisplayName == "Manager")             {                 if (fieldControl.Controls[0].FindControl("UserField") != null)                 {                     PeopleEditor pplEditor = (PeopleEditor)fieldControl.Controls[0].FindControl("UserField");                     if (_ControlMode == SPControlMode.New)                         pplEditor.AutoPostBack = true;                     else                         pplEditor.Enabled = false;                 }             }               //Add JavaScript Event on Dropdown field. Don't forget to add the JavaScript function on the page.             if (_ControlMode == SPControlMode.Edit && fieldDisplayName == "Designation")             {                 DropDownList ddlCategory = (DropDownList)fieldControl.Controls[0];                 ddlCategory.Attributes.Add("onchange", string.Format("javascript:DropdownChangeEvent('{0}');return false;", ddlCategory.ClientID));             }    Following are the screenshots of my Custom ListForm WebPart. Let’s play a game, check out your OOB List forms of SharePoint, compare with these screens and find out differences.   DispForm.aspx:   EditForm.aspx:   NewForm.aspx:   Enjoy the SharePoint Soup!!! ­­­­­­­­­­­­­­­­­­­­

    Read the article

  • Asp.NET custom templated datalist throws argument out of range (index) on button press

    - by MrTortoise
    I have a class BaseTemplate public abstract class BaseTemplate : ITemplate This adds the controls, and provides abstract methods to implement in the inheriting class. The inheriting class then adds its html according to its data source and manages the data binding. This all works fine - I get the control appearing with properly parsed html. The problem is that the base class adds controls into the template that have their own CommandName arguments; the idea is that the class that implements the custom templated dataList will provide the logic of setting the Selected and Edit Indexes. This class also manages the data binding, etc. It sets all of the templates on the datalist in the Init method (which was another cause of this exception). The exception gets thrown when I hit one of these buttons - I have tried hooking up both their click and command events everywhere in case this was the problem. I have also ensured that their command names do not match any of the system ones. The stack trace does not include any references to my methods or objects which is why I am so stuck. It is the most unhelpful message I can imagine. The really frustrating thing is that I cannot get a breakpoint to fire - i.e. the problem is happening after I click the button, but before and of my code can execute. The last time this exception happened was when I had this code in a user control and was assigning the templates to the datalist in the PageLoad. I moved these into init to fix that problem; however, this is a problem that was there then and I have no idea what is causing it let alone how to solve it (and index out of range doesn't really help without knowing what index.) The Exception Details Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index The Stack Trace: [ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index] System.Web.UI.ControlCollection.get_Item(Int32 index) +8665582 System.Web.UI.WebControls.DataList.GetItem(ListItemType itemType, Int32 repeatIndex) +8667655 System.Web.UI.WebControls.DataList.System.Web.UI.WebControls.IRepeatInfoUser.GetItemStyle(ListItemType itemType, Int32 repeatIndex) +11 System.Web.UI.WebControls.RepeatInfo.RenderVerticalRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +8640873 System.Web.UI.WebControls.RepeatInfo.RenderRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +27 System.Web.UI.WebControls.DataList.RenderContents(HtmlTextWriter writer) +208 System.Web.UI.WebControls.BaseDataList.Render(HtmlTextWriter writer) +30 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +163 System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32 System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +51 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Page.Render(HtmlTextWriter writer) +29 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266 The code Base class: public abstract class BaseTemplate : ITemplate { ListItemType _templateType; public BaseTemplate(ListItemType theTemplateType) { _templateType = theTemplateType; } public ListItemType ListItemType { get { return _templateType; } } #region ITemplate Members public void InstantiateIn(Control container) { PlaceHolder ph = new PlaceHolder(); container.Controls.Add(ph); Literal l = new Literal(); switch (_templateType) { case ListItemType.Header: { ph.Controls.Add(new LiteralControl(@"<table><tr>")); InstantiateInHeader(ph); ph.Controls.Add(new LiteralControl(@"</tr>")); break; } case ListItemType.Footer: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInFooter(ph); ph.Controls.Add(new LiteralControl(@"</tr></table>")); break; } case ListItemType.Item: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button select = new Button(); select.ID = "btnSelect"; select.CommandName = "SelectRow"; select.Text = "Select"; ph.Controls.Add(select); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.AlternatingItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInAlternatingItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button select = new Button(); select.ID = "btnSelect"; select.CommandName = "SelectRow"; select.Text = "Select"; ph.Controls.Add(select); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding+=new EventHandler(ph_DataBinding); break; } case ListItemType.SelectedItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button edit = new Button(); edit.ID = "btnEdit"; edit.CommandName = "EditRow"; edit.Text = "Edit"; ph.Controls.Add(edit); Button delete = new Button(); delete.ID = "btnDelete"; delete.CommandName = "DeleteRow"; delete.Text = "Delete"; ph.Controls.Add(delete); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.EditItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInEdit(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button save = new Button(); save.ID = "btnSave"; save.CommandName = "SaveRow"; save.Text = "Save"; ph.Controls.Add(save); Button cancel = new Button(); cancel.ID = "btnCancel"; cancel.CommandName = "CancelRow"; cancel.Text = "Cancel"; ph.Controls.Add(cancel); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.Separator: { InstantiateInSeperator(ph); break; } } } void ph_DataBinding(object sender, EventArgs e) { DataBindingOverride(sender, e); } /// <summary> /// the controls placed into the PlaceHolder will get wrapped in &lt;table&gt;&lt;tr&gt; &lt;/tr&gt;. I.e. you need to provide the column names wrapped in &lt;td&gt;&lt;/td&gt; tags. /// </summary> /// <param name="header"></param> public abstract void InstantiateInHeader(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInItem(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInAlternatingItem(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInEdit(PlaceHolder ph); /// <summary> /// Any html used in the footer will have &lt;/tr&gt;&lt;table&gt; appended to the end. /// &lt;tr&gt; will be appended to the front. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInFooter(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// Adds Delete and Edit Buttons after the table contents. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInSelectedItem(PlaceHolder ph); /// <summary> /// The base class provides no &lt;tr&gt;&lt;/tr&gt; tags /// </summary> /// <param name="ph"></param> public abstract void InstantiateInSeperator(PlaceHolder ph); /// <summary> /// Use this method to bind the controls to their data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public abstract void DataBindingOverride(object sender, EventArgs e); #endregion } Inheriting class: public class NominalGroupTemplate : BaseTemplate { public NominalGroupTemplate(ListItemType theListItemType) : base(theListItemType) { } public override void InstantiateInHeader(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>ID</td><td>Group</td><td>IsPositive</td>")); } public override void InstantiateInItem(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); Label lblGroup = new Label(); lblGroup.ID = "lblGroup"; ph.Controls.Add(lblGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Enabled = false; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInAlternatingItem(PlaceHolder ph) { InstantiateInItem(ph); } public override void InstantiateInEdit(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); TextBox txtGroup = new TextBox(); txtGroup.ID = "txtGroup"; txtGroup.Visible = true; txtGroup.Enabled = true ; ph.Controls.Add(txtGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Visible = true; chkIsPositive.Enabled = true ; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInFooter(PlaceHolder ph) { InstantiateInHeader(ph); } public override void InstantiateInSelectedItem(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); TextBox txtGroup = new TextBox(); txtGroup.ID = "txtGroup"; txtGroup.Visible = true; txtGroup.Enabled = false; ph.Controls.Add(txtGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Visible = true; chkIsPositive.Enabled = false; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInSeperator(PlaceHolder ph) { } public override void DataBindingOverride(object sender, EventArgs e) { PlaceHolder ph = (PlaceHolder)sender; DataListItem li = (DataListItem)ph.NamingContainer; int id = Convert.ToInt32(DataBinder.Eval(li.DataItem, "ID")); string group = (string)DataBinder.Eval(li.DataItem, "Group"); bool isPositive = Convert.ToBoolean(DataBinder.Eval(li.DataItem, "IsPositive")); switch (this.ListItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: { ((Label)ph.FindControl("lblID")).Text = id.ToString(); ((Label)ph.FindControl("lblGroup")).Text = group; ((CheckBox)ph.FindControl("chkIsPositive")).Text = isPositive.ToString(); break; } case ListItemType.EditItem: case ListItemType.SelectedItem: { ((TextBox)ph.FindControl("lblID")).Text = id.ToString(); ((TextBox)ph.FindControl("txtGroup")).Text = group; ((CheckBox)ph.FindControl("chkIsPositive")).Text = isPositive.ToString(); break; } } } } From here I added the control to a page the code behind public partial class NominalGroupbroke : System.Web.UI.UserControl { public void SetNominalGroupList(IList<BONominalGroup> theNominalGroups) { XElement data = Serialiser<BONominalGroup>.SerialiseObjectList(theNominalGroups); ViewState.Add("nominalGroups", data.ToString()); dlNominalGroup.DataSource = theNominalGroups; dlNominalGroup.DataBind(); } protected void Page_init() { dlNominalGroup.HeaderTemplate = new NominalGroupTemplate(ListItemType.Header); dlNominalGroup.ItemTemplate = new NominalGroupTemplate(ListItemType.Item); dlNominalGroup.AlternatingItemTemplate = new NominalGroupTemplate(ListItemType.AlternatingItem); dlNominalGroup.SeparatorTemplate = new NominalGroupTemplate(ListItemType.Separator); dlNominalGroup.SelectedItemTemplate = new NominalGroupTemplate(ListItemType.SelectedItem); dlNominalGroup.EditItemTemplate = new NominalGroupTemplate(ListItemType.EditItem); dlNominalGroup.FooterTemplate = new NominalGroupTemplate(ListItemType.Footer); } protected void Page_Load(object sender, EventArgs e) { dlNominalGroup.ItemCommand += new DataListCommandEventHandler(dlNominalGroup_ItemCommand); } void dlNominalGroup_Init(object sender, EventArgs e) { dlNominalGroup.HeaderTemplate = new NominalGroupTemplate(ListItemType.Header); dlNominalGroup.ItemTemplate = new NominalGroupTemplate(ListItemType.Item); dlNominalGroup.AlternatingItemTemplate = new NominalGroupTemplate(ListItemType.AlternatingItem); dlNominalGroup.SeparatorTemplate = new NominalGroupTemplate(ListItemType.Separator); dlNominalGroup.SelectedItemTemplate = new NominalGroupTemplate(ListItemType.SelectedItem); dlNominalGroup.EditItemTemplate = new NominalGroupTemplate(ListItemType.EditItem); dlNominalGroup.FooterTemplate = new NominalGroupTemplate(ListItemType.Footer); } void dlNominalGroup_DataBinding(object sender, EventArgs e) { } void deleteNominalGroup(int index) { XElement data = XElement.Parse(Convert.ToString( ViewState["nominalGroups"] )); IList<BONominalGroup> list = Serialiser<BONominalGroup>.DeserialiseObjectList(data); FENominalGroup.DeleteNominalGroup(list[index].ID); list.RemoveAt(index); data = Serialiser<BONominalGroup>.SerialiseObjectList(list); ViewState["nominalGroups"] = data.ToString(); dlNominalGroup.DataSource = list; dlNominalGroup.DataBind(); } void updateNominalGroup(DataListItem theItem) { XElement data = XElement.Parse(Convert.ToString( ViewState["nominalGroups"])); IList<BONominalGroup> list = Serialiser<BONominalGroup>.DeserialiseObjectList(data); BONominalGroup old = list[theItem.ItemIndex]; BONominalGroup n = new BONominalGroup(); byte id = Convert.ToByte(((TextBox)theItem.FindControl("lblID")).Text); string group = ((TextBox)theItem.FindControl("txtGroup")).Text; bool isPositive = Convert.ToBoolean(((CheckBox)theItem.FindControl("chkIsPositive")).Text); n.ID = id; n.Group = group; n.IsPositive = isPositive; FENominalGroup.UpdateNominalGroup(old, n); list[theItem.ItemIndex] = n; data = Serialiser<BONominalGroup>.SerialiseObjectList(list); ViewState["nominalGroups"] = data.ToString(); } void dlNominalGroup_ItemCommand(object source, DataListCommandEventArgs e) { DataList l = (DataList)source; switch (e.CommandName) { case "SelectRow": { if (l.EditItemIndex == -1) { l.SelectedIndex = e.Item.ItemIndex; l.EditItemIndex = -1; } break; } case "EditRow": { if (l.SelectedIndex == e.Item.ItemIndex) { l.EditItemIndex = e.Item.ItemIndex; } break; } case "DeleteRow": { deleteNominalGroup(e.Item.ItemIndex); l.EditItemIndex = -1; try { l.SelectedIndex = e.Item.ItemIndex; } catch { l.SelectedIndex = -1; } break; } case "CancelRow": { l.SelectedIndex = l.EditItemIndex; l.EditItemIndex = -1; break; } case "SaveRow": { updateNominalGroup(e.Item); try { l.SelectedIndex = e.Item.ItemIndex; } catch { l.SelectedIndex = -1; } l.EditItemIndex = -1; break; } } } Lots of code there, I'm afraid, but it should build. Thanks if anyone manages to spot my silliness. The BONominalGroup class (please ignore my crazy getHash override, I'm not proud of it). IAudit can just be an empty interface here and all will be fine. It used to inherit from another class, I have cleaned that out - so the serialization logic may be broken here. public class BONominalGroup { public BONominalGroup() #region Fields and properties private Int16 _ID; public Int16 ID { get { return _ID; } set { _ID = value; } } private string _group; public string Group { get { return _group; } set { _group = value; } } private bool _isPositve; public bool IsPositive { get { return _isPositve; } set { _isPositve = value; } } #endregion public override bool Equals(object obj) { bool retVal = false; BONominalGroup ng = obj as BONominalGroup; if (ng!=null) if (ng._group == this._group && ng._ID == this.ID && ng.IsPositive == this.IsPositive) { retVal = true; } return retVal; } public override int GetHashCode() { return ToString().GetHashCode(); } public override string ToString() { return "BONominalGroup{ID:" + this.ID.ToString() + ",Group:" + this.Group.ToString() + ",IsPositive:" + this.IsPositive.ToString() + "," + "}"; } #region IXmlSerializable Members public override void ReadXml(XmlReader reader) { reader.ReadStartElement("BONominalGroup"); this.ID = Convert.ToByte(reader.ReadElementString("id")); this.Group = reader.ReadElementString("group"); this.IsPositive = Convert.ToBoolean(reader.ReadElementString("isPositive")); base.ReadXml(reader); reader.ReadEndElement(); } public override void WriteXml(XmlWriter writer) { writer.WriteElementString("id", this.ID.ToString()); writer.WriteElementString("group", this.Group); writer.WriteElementString("isPositive", this.IsPositive.ToString()); // writer.WriteStartElement("BOBase"); // base.WriteXml(writer); writer.WriteEndElement(); } #endregion }

    Read the article

  • Detecting controls of a winform

    - by Ayush Saxena
    I have a circular area cursor which is a circular winform(translucent) hooked to a cursor. On click, I want to get hold of the controls in the region of the parent winform just below the area of the cursor/form. These controls have to be arranged in circular layout on a different form. I am working on C#.NET. Please tell how to access the controls of a winform and change their positions in context with my application described above. Like what classes, procedure , resources i need. I am a newbie but desperate to complete this task.thanks in advance.

    Read the article

  • Change players state and controls in-game

    - by Samurai Fox
    I'm using Unity 3D Let's say the player is an ice cube. You control it like a normal player. On press of a button, ice transforms (with animation) into water. You control it completely different than the ice cube. Another great example would be: Player is human being and has normal FPS controls. On press of a button human transforms into birds and now has completely different controls. Now, my question is, what would be easier and better: make one object with animation transition and to stay in that state of anim. until button is pressed again make two object: ice and water. Ice has an animation of turning into water. So replace ice (with animation) with water object And if anyone knows this one too: how to switch between 2 different types of player controls.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >