Search Results

Search found 164 results on 7 pages for 'databound'.

Page 6/7 | < Previous Page | 2 3 4 5 6 7  | Next Page >

  • ASP.Net Problem with Event Handlers and Control Creation Timing

    - by Oliver Weichhold
    What I am trying to achieve here is to display a number of LinkButtons in a RadGrid Column. The buttons are generated from a collection property member of the bound grid row item. The CollectionLinkButton control is nothing more than a asp:Panel derived control that populates its Child Controls from "DataItem.SomeCollection" and this is working fine. The problem I am facing is with this part: Collection='<%# DataBinder.Eval(Container, "DataItem.SomeCollection") %' This is because databound Collection Property is populated so late in the lifecycle of the page that the LinkButton Controls that the CollectionLinkButton class creates from the collection are not available yet during Postback when the Click event Handler is supposed to fire and I have currently no idea how to solve this problem. <radG:RadGrid ID="grid" runat="server" DataSourceID="ds_AB"> <MasterTableView> <Columns> <radG:GridTemplateColumn> <ItemTemplate> <local:CollectionLinkButton ID="LinkButton1" runat="server" CssClass="EntityLinkButton" Collection='<%# DataBinder.Eval(Container, "DataItem.SomeCollection") %>' CollectionProperty="Id" CollectionDisplayProperty="Name" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'</local:CollectionLinkButton> </ItemTemplate> </radG:GridTemplateColumn>

    Read the article

  • Dynamic Control loading at wrong time?

    - by Telos
    This one is a little... odd. Basically I have a form I'm building using ASP.NET Dynamic Data, which is going to utilize several custom field templates. I've just added another field to the FormView, with it's own custom template, and the form is loading that control twice for no apparent reason. Worse yet, the first time it loads the template, the Row is not ready yet and I get the error message: {"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."} I'm accessing the Row variable in a LinqDataSource OnSelected event in order to get the child object... Now for the wierd part: If I reorder the fields a little, the one causing the problem no longer gets loaded twice. Any thoughts? EDIT: I've noticed that Page_Load gets called on the first load (when Row throws an exception if you try to use it) but does NOT get called the second time around. If that helps any... Right now managing it by just catching and ignoring the exception, but still a little worried that things will break if I don't find the real cause. EDIT 2: I've traced the problem to using FindControl recursively to find other controls on the page. Apparently FindControl can cause the page lifecycle events (at least up to page_load) to fire... and this occurs before that page "should" be loading so it's dynamic data "stuff" isn't ready yet.

    Read the article

  • ASP:DropDownList in ItemTemplate: Why is SelectedValue attribute allowed?

    - by recursive
    This piece of code <asp:DropDownList runat="server" ID="testdropdown" SelectedValue="2"> <asp:ListItem Text="1" Value="1"></asp:ListItem> <asp:ListItem Text="2" Value="2"></asp:ListItem> <asp:ListItem Text="3" Value="3"></asp:ListItem> </asp:DropDownList> yields this error: The 'SelectedValue' property cannot be set declaratively. Yet, this is a legal and commonly used edit template for databound GridViews. The SelectedValue attribute certainly appears to be declaratively set here. <EditItemTemplate> <asp:DropDownList runat="server" ID="GenreDropDownList" DataSourceID="GenreDataSource" DataValueField="GenreId" DataTextField="Name" SelectedValue='<%# Bind("Genre.GenreId") %>'> </asp:DropDownList> </EditItemTemplate> The question is: what is the difference between the cases when you are allowed to set it declaratively and those in which you are not? The error message implies that it's never allowed.

    Read the article

  • How to set image Tag URLs programmatically in ASP.NET C# inside of a ListView Control?

    - by loyalpenguin
    Hi, I know how you can set an tag's url attribute programmatically in c#, but it seems when I try to access the image element inside of a tag I cannot access it. The is residing in the . NOTE: I am only having this issue inside the Now the ListView tag is also databound.(this is probably why I cannot access, because it isn't guaranteed that it will even exist perhaps). How can I get around this so that I can display my images programmatically or is there a better solution? Here's the source: <asp:ListView ID="ListView_Comments" runat="server" DataKeyNames="ReviewID,ProductID,Rating" DataSourceID="EDS_CommentsList"> <ItemTemplate> <tr style="background-color:#EDECB3;color: #000000;"> <td><%# Eval("CustomerName") %></td> <td> <img src='Styles/Images/ReviewRating_d<%# Eval("Rating") %>.gif' alt=""> <br /> </td> <td> <%# Eval("Comments") %> </td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr style="background-color:#F8F8F8;"> <td><%# Eval("CustomerName") %></td> <td> <img id="rateImage" src="" alt="" runat="server" /> ......

    Read the article

  • How can I clear viewstate of a dropdownlist inside a usercontrol? Should I?

    - by tbilly
    I have a web user control with a dropdownlist inside of it. When the usercontrol's databind event is called, it automatically fires the dropdownlists databind event. In the dropdownlist's ondatabound event handler an 'other' option is appended to the end of the dropdownlist. The usercontrol is loaded multiple times, depending on selection of other controls on the page. When the page loads initially, there are no items in the usercontrol except the 'other' option. Then when I call the user control's databind event the control reloads, with 4 items plus the 'other' option. The text for the first item in the list is the 'other' option's text, not what it should be. I've stepped through the databound event of the dropdownlist and have found that all items are loading correctly. It appears that the dropdownlist's viewstate is the culprit, that the dropdownlist's original item[1] text is overwriting the new text. I've tried disabling viewstate on the dropdownlist, but then it wouldn't load at all. Should I try to clear the dropdownlist's viewstate? How do I do that? Any suggestions would be greatly appreciated.

    Read the article

  • ASP.NET Repeater - Evaluate Item as int?

    - by WedTM
    I'm trying to style a table row based upon a value in the databound collection (from LINQ to SQL) in my item template, however it's not working. This is what I have so far: <ItemTemplate> <% string style = String.Empty; if ((string)DataBinder.Eval(Quotes.Cu, "Status") == "Rejected") style = "color:red;"; else if ((string)Eval("Priority") == "Y") style = "color:green;"; if (style == String.Empty) Response.Write("<tr>"); else Response.Write("<tr style=\"" + style + "\""); %> <td> <%# Eval("QuoteID") %> </td> <td> <%# Eval("DateDue", "{0:dd/MM/yyyy}") %> </td> <td> <%# Eval("Company") %> </td> <td> <%# Eval("Estimator") %> </td> <td> <%# Eval("Attachments") %> </td> <td> <%# Eval("Employee") %> </td> </tr> </ItemTemplate>

    Read the article

  • Avoiding mass propagation of properties and events for exposure to ViewModels.

    - by firoso
    I have an MVVM application I am developing that is to the point where I'm ready to start putting together a user interface (my client code is largely functional) I'm now running into the issue that I'm trying to get my application data to where I need it so that it can be consumed by the view model and then bound to the view. Unfortunately, it seems that I've either got a few structural oversights, or I'm just going to have to face the reality that I need to be propogating events and raising excessive amounts of errors to notify view models that thier properties have changed. Let me go into some examples of my issue: I have a class "Unit" contained in a class "Test", contained in a class "Session" contained in a class "TestManager" which is contained in "TestDataModel" which is utilized by "TestViewModel" which is databound to by my "TestView" .... WHOA. Now, consider that Unit (the bottom of the heiarchy) has a property called "Results" that is updated periodically, I want to expose that to my viewmodel and then databind it to my view, trouble is, the only way I can really think to do this is to perpetuate events WAY up a chain that say "I've been updated!" and then request the new value... This seems like an aweful way to do this. Alternatively, I could register a static event and raise it, and have the appropriate "Unit view model" grab the event and request the update. This SEEMS better... but... static events? Is that a taboo idea? Also, having an expression like: TestDataModel.TestManager.Session.Test.Unit.Results[i] Seems REALLY gross to have on a View Model. I know this all reeks of a bad design issue, but I can't figure out what I did wrong? Should I be using more singleton/container controlled lifetimes type objects? Register object instances with static helper containers? Obviously these are hard questions to answer without being intimate with the existing structure, but if you've run into situations like this, what did you do to refactor? Should I just live with this, add mass events, and propogate them?

    Read the article

  • DataTrigger not reevaluating after property changes

    - by frozen
    I have a listbox which has its itemssource (this is done in the code behind on as the window is created) databound to an observable collection. The List box then has the following data template assigned against the items: usercontrol.xaml ... <ListBox x:Name="communicatorListPhoneControls" ItemContainerStyle="{StaticResource templateForCalls}"/> ... app.xaml ... <Style x:Key="templateForCalls" TargetType="{x:Type ListBoxItem}"> <Setter Property="ContentTemplate" Value="{StaticResource templateRinging}"/> <Style.Triggers> <DataTrigger Binding="{Binding Path=hasBeenAnswered}" Value="True"> <Setter Property="ContentTemplate" Value="{StaticResource templateAnswered}"/> </DataTrigger> </Style.Triggers> </Style> ... When the observable collection is updated with an object, this appears in the listbox with the correct initial datatemplate, however when the "hasBeenAnswered" property is set to true (when debugging i can see the collection is correct) the datatrigger does not re-evaluate and then update the listbox to use the correct data template. I have implemented the INotifyPropertyChanged Event in my object, and if in the template i bind to a value, i can see the value update. Its just that the datatrigger will not re-evaluate and change to the correct template. I know the datatrigger binding is correct because if i close the window and open it again, it will correctly apply the second datatemplate, because the "hasBeenAnswered" is set to True.

    Read the article

  • Can I get away with this or is it just too crude and unpractical ?

    - by The_AlienCoder
    I spent the whole of last night searching for a free AspNet web chat control that I could simply drag into my website. Well the search was in vain as I could not find a control that matched my needs i.e List of users, 1 to 1 chat, Ability to kick out users.. In the end I decided to create my own control from scractch. Although it works well on my machine Im concerned that It maybe a little crude and unpractical on a shared hosting enviroment. Basically this is what I did : Created an sql database that stores the chat messages. Wrote the stored procedures and and included a statement that clears old messages Then the 'crude' part : Dragged an update panel and timer control on my page Dragged a Repeater databound to the chat messages table inside the update panel Dragged another update panel and inside it put a textbox and a button Configured the timer control to tick every 5 seconds. ..and then I made it all work like this In the timer tick event I 'refreshed' the messages display by invoking Databind() on my repeater i.e protected void Timer1_Tick(object sender, EventArgs e) { MyRepeater.DataBind(); } Then in my send button click event protected void btnSend_Click(object sender, EventArgs e) { MyDataLayer.InsertMessage(Message, Sender, CurrTime); } Well It works well on my machine and Ive got the other functionalities(users list, kick out user..) to work by simply creating more tables. But like I said it seems a little crude to me. so I need a proffesional opinion. Should I run with this or try another Approach ?

    Read the article

  • MS Access Form - Horizontal Anchor Affecting Data Update

    - by nicholas
    Running Access 2007 with a databound form. The form Record Source is set to a query, and all fields in the form have a defined Control Source; nothing fancy, just field names. The form is a Single form with record navigation buttons which perform a "Next Record" and "Previous Record" actions. As I navigate the records the controls in the header update correctly. However, if I change a control Horizontal Anchor property to "Right" the fields no longer update on record navigation. This is observed for both text box and combo box controls. I can switch the anchoring back to "Left" and the updating works as it should. Is there some reason anchoring would affect a control updating of in an Access form? Or is this a bug that has been observed before? The only workaround I can think of is to assign the control text/value property in the form OnCurrent event, but this seems somewhat sloppy. Am I missing something here?

    Read the article

  • Why does a checkbox remain checked in FF3 but not in IE, Chrome or ...

    - by sirrocco
    So - I have a checkbox <asp:CheckBox ID="chkOrder" runat="server" Visible='<%#IsCheckBoxVisible() %>' Checked="false" OnCheckedChanged="chkOrder_CheckedChanged" AutoPostBack="true" EnableViewState="false"></asp:CheckBox> the one above. Now, the checkbox is in a gridview and on databound - for all the rows in the gridview the checkbox is set to false. The problem is that the first checkbox is still true checked. In IE the problem doesn't exist, same for Chrome. I'm running out of options. Also if i use $("checkboxName").attr("checked"); // verified on jquery ready function. In FF it is true; IE false; Chrome false. Any tips? EDIT Now get ready for this : in the generated html - there is NO checked attribute. The diff between FF and IE is exactly the same. Another thing - the grid that contains the checkboxes has an ajax panel on it and when I page the grid, try to go to page 2 - the checkedChanged in codebehind is triggered.

    Read the article

  • Cast exception being generated when using the same type of object

    - by David Tunnell
    I was previously using static variables to hold variable data that I want to save between postbacks. I was having problems and found that the data in these variables is lost when the appdomain ends. So I did some research and decided to go with ViewStates: static Dictionary<string, linkButtonObject> linkButtonDictonary; protected void Page_Load(object sender, EventArgs e) { if (ViewState["linkButtonDictonary"] != null) { linkButtonDictonary = (Dictionary<string, linkButtonObject>)ViewState["linkButtonDictonary"]; } else { linkButtonDictonary = new Dictionary<string, linkButtonObject>(); } } And here is the very simple class I use: [Serializable] public class linkButtonObject { public string storyNumber { get; set; } public string TaskName { get; set; } } I am adding to linkButtonDictionary as a gridview is databound: protected void hoursReportGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton btn = (LinkButton)e.Row.FindControl("taskLinkButton"); linkButtonObject currentRow = new linkButtonObject(); currentRow.storyNumber = e.Row.Cells[3].Text; currentRow.TaskName = e.Row.Cells[5].Text; linkButtonDictonary.Add(btn.UniqueID, currentRow); } } It appears that my previous issues are resolved however a new one has arisin. Sometime when I postback I am getting this error: [A]System.Collections.Generic.Dictionary2[System.String,linkButtonObject] cannot be cast to [B]System.Collections.Generic.Dictionary2[System.String,linkButtonObject]. Type A originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Type B originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. I don't understand how there can be a casting issue when I am using the same class everywhere. What am I doing wrong and how do I fix it?

    Read the article

  • <%: %> brackets for HTML Encoding in ASP.NET 4.0

    - by Slauma
    Accidentally I found this post about a new feature in ASP.NET 4.0: Expressions enclosed in these new brackets <%: Content %> should be rendered as HTML encoded. I've tried this within a databound label in a FormView like so: <asp:Label ID="MyLabel" runat="server" Text='<%: Eval("MyTextProperty") %>' /> But it doesn't work: The text property contains script tags (for testing), but the output is blank. Using the traditional way works: <asp:Label ID="MyLabel" runat="server" Text='<%# HttpUtility.HtmlEncode(Eval("MyTextProperty")) %>' /> What am I doing wrong? (On a sidenote: I am too stupid to find any information: Google refuses to search for that thing. The VS2010 Online help on MSDN offers a lot of hits, but nothing related to my search. Stackoverflow search too. And I don't know how these "things" (the brackets I mean) are officially called to have a better search term.) Any info and additional links and resources are welcome! Thanks in advance!

    Read the article

  • ComboBox Data Binding

    - by Geertjan
    Let's create a databound combobox, levering MVC in a desktop application. The result will be a combobox, provided by the NetBeans ChoiceView, that displays data retrieved from a database: What follows is not much different from the NetBeans Platform CRUD Application Tutorial and you're advised to consult that document if anything that follows isn't clear enough. One kind of interesting thing about the instructions that follow is that it shows that you're able to create an application where each element of the MVC architecture can be located within a separate module: Start by creating a new NetBeans Platform application named "MyApplication". Model We're going to start by generating JPA entity classes from a database connection. In the New Project wizard, choose "Java Class Library". Click Next. Name the Java Class Library "MyEntities". Click Finish. Right-click the MyEntities project, choose New, and then select "Entity Classes from Database". Work through the wizard, selecting the tables of interest from your database, and naming the package "entities". Click Finish. Now a JPA entity is created for each of the selected tables. In the Project Properties dialog of the project, choose "Copy Dependent Libraries" in the Packaging panel. Build the project. In your project's "dist" folder (visible in the Files window), you'll now see a JAR, together with a "lib" folder that contains the JARs you'll need. In your NetBeans Platform application, create a module named "MyModel", with code name base "org.my.model". Right-click the project, choose Properties, and in the "Libraries" panel, click Add Dependency button in the Wrapped JARs subtab to add all the JARs from the previous step to the module. Also include "derby-client.jar" or the equivalent driver for your database connection to the module. Controler In your NetBeans Platform application, create a module named "MyControler", with code name base "org.my.controler". Right-click the module's Libraries node, in the Projects window, and add a dependency on "Explorer & Property Sheet API". In the MyControler module, create a class with this content: package org.my.controler; import org.openide.explorer.ExplorerManager; public class MyUtils { static ExplorerManager controler; public static ExplorerManager getControler() { if (controler == null) { controler = new ExplorerManager(); } return controler; } } View In your NetBeans Platform application, create a module named "MyView", with code name base "org.my.view".  Create a new Window Component, in "explorer" view, for example, let it open on startup, with class name prefix "MyView". Add dependencies on the Nodes API and on the Explorer & Property Sheet API. Also add dependencies on the "MyModel" module and the "MyControler" module. Before doing so, in the "MyModel" module, make the "entities" package and the "javax.persistence" packages public (in the Libraries panel of the Project Properties dialog) and make the one package that you have in the "MyControler" package public too. Define the top part of the MyViewTopComponent as follows: public final class MyViewTopComponent extends TopComponent implements ExplorerManager.Provider { ExplorerManager controler = MyUtils.getControler(); public MyViewTopComponent() { initComponents(); setName(Bundle.CTL_MyViewTopComponent()); setToolTipText(Bundle.HINT_MyViewTopComponent()); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); controler.setRootContext(new AbstractNode(Children.create(new ChildFactory<Customer>() { @Override protected boolean createKeys(List list) { EntityManager entityManager = Persistence. createEntityManagerFactory("MyEntitiesPU").createEntityManager(); Query query = entityManager.createNamedQuery("Customer.findAll"); list.addAll(query.getResultList()); return true; } @Override protected Node createNodeForKey(Customer key) { Node customerNode = new AbstractNode(Children.LEAF, Lookups.singleton(key)); customerNode.setDisplayName(key.getName()); return customerNode; } }, true))); controler.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { Customer selectedCustomer = controler.getSelectedNodes()[0].getLookup().lookup(Customer.class); StatusDisplayer.getDefault().setStatusText(selectedCustomer.getName()); } }); JPanel row1 = new JPanel(new FlowLayout(FlowLayout.LEADING)); row1.add(new JLabel("Customers: ")); row1.add(new ChoiceView()); add(row1); } @Override public ExplorerManager getExplorerManager() { return controler; } ... ... ... Now run the application and you'll see the same as the image with which this blog entry started.

    Read the article

  • MVVM load data during or after ViewModel construction?

    - by mkmurray
    My generic question is as the title states, is it best to load data during ViewModel construction or afterward through some Loaded event handling? I'm guessing the answer is after construction via some Loaded event handling, but I'm wondering how that is most cleanly coordinated between ViewModel and View? Here's more details about my situation and the particular problem I'm trying to solve: I am using the MVVM Light framework as well as Unity for DI. I have some nested Views, each bound to a corresponding ViewModel. The ViewModels are bound to each View's root control DataContext via the ViewModelLocator idea that Laurent Bugnion has put into MVVM Light. This allows for finding ViewModels via a static resource and for controlling the lifetime of ViewModels via a Dependency Injection framework, in this case Unity. It also allows for Expression Blend to see everything in regard to ViewModels and how to bind them. So anyway, I've got a parent View that has a ComboBox databound to an ObservableCollection in its ViewModel. The ComboBox's SelectedItem is also bound (two-way) to a property on the ViewModel. When the selection of the ComboBox changes, this is to trigger updates in other views and subviews. Currently I am accomplishing this via the Messaging system that is found in MVVM Light. This is all working great and as expected when you choose different items in the ComboBox. However, the ViewModel is getting its data during construction time via a series of initializing method calls. This seems to only be a problem if I want to control what the initial SelectedItem of the ComboBox is. Using MVVM Light's messaging system, I currently have it set up where the setter of the ViewModel's SelectedItem property is the one broadcasting the update and the other interested ViewModels register for the message in their constructors. It appears I am currently trying to set the SelectedItem via the ViewModel at construction time, which hasn't allowed sub-ViewModels to be constructed and register yet. What would be the cleanest way to coordinate the data load and initial setting of SelectedItem within the ViewModel? I really want to stick with putting as little in the View's code-behind as is reasonable. I think I just need a way for the ViewModel to know when stuff has Loaded and that it can then continue to load the data and finalize the setup phase. Thanks in advance for your responses.

    Read the article

  • ASP.NET GridView second header row to span main header row

    - by Dana Robinson
    I have an ASP.NET GridView which has columns that look like this: | Foo | Bar | Total1 | Total2 | Total3 | Is it possible to create a header on two rows that looks like this? | | Totals | | Foo | Bar | 1 | 2 | 3 | The data in each row will remain unchanged as this is just to pretty up the header and decrease the horizontal space that the grid takes up. The entire GridView is sortable in case that matters. I don't intend for the added "Totals" spanning column to have any sort functionality. Edit: Based on one of the articles given below, I created a class which inherits from GridView and adds the second header row in. namespace CustomControls { public class TwoHeadedGridView : GridView { protected Table InnerTable { get { if (this.HasControls()) { return (Table)this.Controls[0]; } return null; } } protected override void OnDataBound(EventArgs e) { base.OnDataBound(e); this.CreateSecondHeader(); } private void CreateSecondHeader() { GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal); TableCell left = new TableHeaderCell(); left.ColumnSpan = 3; row.Cells.Add(left); TableCell totals = new TableHeaderCell(); totals.ColumnSpan = this.Columns.Count - 3; totals.Text = "Totals"; row.Cells.Add(totals); this.InnerTable.Rows.AddAt(0, row); } } } In case you are new to ASP.NET like I am, I should also point out that you need to: 1) Register your class by adding a line like this to your web form: <%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%> 2) Change asp:GridView in your previous markup to foo:TwoHeadedGridView. Don't forget the closing tag. Another edit: You can also do this without creating a custom class. Simply add an event handler for the DataBound event of your grid like this: protected void gvOrganisms_DataBound(object sender, EventArgs e) { GridView grid = sender as GridView; if (grid != null) { GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal); TableCell left = new TableHeaderCell(); left.ColumnSpan = 3; row.Cells.Add(left); TableCell totals = new TableHeaderCell(); totals.ColumnSpan = grid.Columns.Count - 3; totals.Text = "Totals"; row.Cells.Add(totals); Table t = grid.Controls[0] as Table; if (t != null) { t.Rows.AddAt(0, row); } } } The advantage of the custom control is that you can see the extra header row on the design view of your web form. The event handler method is a bit simpler, though.

    Read the article

  • Shawn Wildermuth violating MVVM in MSDN article?

    - by rasx
    This may be old news but back in March 2009, Shawn Wildermuth, his article, “Model-View-ViewModel In Silverlight 2 Apps,” has a code sample that includes DataServiceEntityBase: // COPIED FROM SILVERLIGHTCONTRIB Project for simplicity /// <summary> /// Base class for DataService Data Contract classes to implement /// base functionality that is needed like INotifyPropertyChanged. /// Add the base class in the partial class to add the implementation. /// </summary> public abstract class DataServiceEntityBase : INotifyPropertyChanged { /// <summary> /// The handler for the registrants of the interface's event /// </summary> PropertyChangedEventHandler _propertyChangedHandler; /// <summary> /// Allow inheritors to fire the event more simply. /// </summary> /// <param name="propertyName"></param> protected void FirePropertyChanged(string propertyName) { if (_propertyChangedHandler != null) { _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #region INotifyPropertyChanged Members /// <summary> /// The interface used to notify changes on the entity. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChangedHandler += value; } remove { _propertyChangedHandler -= value; } } #endregion What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons why Shawn would go this way: what Shawn can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework): // Partial Method to support the INotifyPropertyChanged interface public partial class Game : DataServiceEntityBase { #region Partial Method INotifyPropertyChanged Implementation // Override the Changed partial methods to implement the // INotifyPropertyChanged interface // This helps with the Model implementation to be a mostly // DataBound implementation partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); } partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); } partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); } partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); } partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); } partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); } partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); } partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); } partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); } partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); } partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); } partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); } partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); } partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); } partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); } #endregion } Of course MSDN code can seen as “toy code” for educational purposes but is anyone doing anything like this in the real world of Silverlight development?

    Read the article

  • Pass or Get a value from Parent ViewModel down to Sub-ViewModel?

    - by mkmurray
    I am using the MVVM Light framework as well as Unity for DI. I have some nested Views, each bound to a corresponding ViewModel. The ViewModels are bound to each View's root control DataContext via the ViewModelLocator idea that Laurent Bugnion has put into MVVM Light. This allows for finding ViewModels via a static resource and for controlling the lifetime of ViewModels via a Dependency Injection framework, in this case Unity. It also allows for Expression Blend to see everything in regard to ViewModels and how to bind them. As I stated the Views have a healthy dose of nesting, but the ViewModels don't really know anything about each other. A parent view binds to its corresponding ViewModel via the static resource ViewModelLocator (which uses Unity to control the construction and lifetime of the ViewModel object). That parent view contains a user control in it that is another sub-view, which then goes and gets its corresponding ViewModel via the ViewModelLocator as well. The ViewModels don't have references to each other or know any hierarchy in regard to each other. So here's an example of how the ViewModels do interact via messaging. I've got a parent View that has a ComboBox databound to an ObservableCollection in its ViewModel. The ComboBox's SelectedItem is also bound (two-way) to a property on the ViewModel. When the selection of the ComboBox changes, this is to trigger updates in other Views and sub-Views. Currently I am accomplishing this via the Messaging system that is found in MVVM Light. So I'm wondering what the best practice would be to get information from one ViewModel to another? In this case, what I need to pass down to sub-ViewModels is basically a user Guid representing the currently logged in user. The top-most parent View (well, ViewModel) will know this information, but I'm not sure how to get it down into the sub-ViewModels. Some possible approaches I can think of: Should the sub-ViewModel ask the static resource ViewModelLocator for a reference to the same object the parent View is using and access the property that way? It seems like ViewModels going through each other's properties is not very clean and couples them together unnecessarily. I'm already using messaging to notify the sub-Views that the user selected a new item in the ComboBox and to update accordingly. But the object type that is being selected in the ComboBox is not really directly related to this data value that the sub-Views need.

    Read the article

  • Enable 2-way databinding on nested listview

    - by Lars Pedersen
    I have a ASP.NET FormView, that - via an ObjectDataSource - is bound to my EventOrder-object: [Serializable] public class EventOrder { [Serializable] public class OrderTicket { public int Qty { get; set; } public int Id { get { return this.Ticket.Id; } } public Ticket Ticket { get; set; } public double TicketPrice { get; set; } } [Serializable] public class OrderExtra { public int Qty { get; set; } public int Id { get { return this.Extra.Id; } } public Extra Extra { get; set; } } public Event Event { get; set; } public List<OrderTicket> OrderTickets { get; set; } public List<OrderExtra> OrderExtras { get; set; } public UserProfile UserProfile { get; set; } public List<Fee> Fees { get; set; } public List<Discount> Discounts { get; set; } public EventOrder() { this.OrderExtras = new List<OrderExtra>(); this.OrderTickets = new List<OrderTicket>(); this.Fees = new List<Fee>(); this.Discounts = new List<Discount>(); } } In my FormView, I have a bindingexpression on an inner listview for my collection of OrderTickets: <asp:ListView Visible="false" runat="server" DataKeyNames="Id" ID="lvTickets" DataSource='<%# Bind("OrderTickets") %>'> <ItemTemplate> <asp:TextBox ID="TextBox5" Text='<%# Bind("Qty") %>' runat="server"></asp:TextBox> <asp:Label ID="Label1" runat="server" Text='<%# Eval("Ticket.Title") %>'></asp:Label> <asp:Label ID="Label2" runat="server" Text='<%# Eval("TicketPrice") %>'></asp:Label><br /> </ItemTemplate> My problem is that the Qty-property isn't databound to the object when the parent container is updated. Is it possible to have this kind of parent-child relation with 2-way databinding? Can I force the child listview to update it's bound dataobject when I submit the form?

    Read the article

  • Does this MSDN article violate MVVM?

    - by rasx
    This may be old news but back in March 2009, this article, “Model-View-ViewModel In Silverlight 2 Apps,” has a code sample that includes DataServiceEntityBase: // COPIED FROM SILVERLIGHTCONTRIB Project for simplicity /// <summary> /// Base class for DataService Data Contract classes to implement /// base functionality that is needed like INotifyPropertyChanged. /// Add the base class in the partial class to add the implementation. /// </summary> public abstract class DataServiceEntityBase : INotifyPropertyChanged { /// <summary> /// The handler for the registrants of the interface's event /// </summary> PropertyChangedEventHandler _propertyChangedHandler; /// <summary> /// Allow inheritors to fire the event more simply. /// </summary> /// <param name="propertyName"></param> protected void FirePropertyChanged(string propertyName) { if (_propertyChangedHandler != null) { _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #region INotifyPropertyChanged Members /// <summary> /// The interface used to notify changes on the entity. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChangedHandler += value; } remove { _propertyChangedHandler -= value; } } #endregion What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons Why would we go this way: what we can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework): // Partial Method to support the INotifyPropertyChanged interface public partial class Game : DataServiceEntityBase { #region Partial Method INotifyPropertyChanged Implementation // Override the Changed partial methods to implement the // INotifyPropertyChanged interface // This helps with the Model implementation to be a mostly // DataBound implementation partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); } partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); } partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); } partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); } partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); } partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); } partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); } partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); } partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); } partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); } partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); } partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); } partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); } partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); } partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); } #endregion } Of course MSDN code can seen as “toy code” for educational purposes but is anyone doing anything like this in the real world of Silverlight development?

    Read the article

  • Asp.Net GridView

    - by user329419
    I need to hide columns in GridView Then access the values of these in the GridViewSelectedIndexChanged using vb.net. When I set DataBound columns is false cant acces the values. Please help. <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BorderStyle="Outset" CellPadding="4" DataSourceID="odsA02_Tracking" Font-Size="Small" ForeColor="#333333" GridLines="Vertical" Style="border-right: #0000ff thin solid; table-layout: auto; border-top: #0000ff thin solid; font-size: x-small; border-left: #0000ff thin solid; border-bottom: #0000ff thin solid; font-family: Arial; border-collapse: separate" PageSize="30"> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:BoundField DataField="Since" HeaderText="Submit Date" ReadOnly="True" SortExpression="Since" /> <asp:BoundField DataField="Started_By" HeaderText="Submitted By" SortExpression="Started_By" /> <asp:BoundField DataField="FullName" HeaderText="Client Name" ReadOnly="True" SortExpression="FullName" /> <asp:BoundField DataField="Product_Desc" HeaderText="Product" ReadOnly="True" SortExpression="Product_Desc" /> <asp:BoundField DataField="Branch_List" HeaderText="Branch" ReadOnly="True" SortExpression="Branch_List" /> <asp:BoundField DataField="Event_AssignedID" HeaderText="Assigned To" ReadOnly="True" SortExpression="Event_AssignedID" /> <asp:BoundField DataField="DaysElapsed" HeaderText="Days Open" ReadOnly="True" SortExpression="DaysElapsed" /> <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" /> <asp:BoundField DataField="Instance_ID" HeaderText="Instance_ID" SortExpression="Instance_ID" Visible=True /> <asp:TemplateField Visible=False> <ItemTemplate> <asp:HiddenField ID=hdnSeqID Value='<%#Eval("Seq_ID") %>' runat=server/> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="FormCode" Visible=false> <ItemTemplate> <asp:HiddenField ID=hdnFormCode Value='<%#Eval("Form_Code") %>' runat=server/> </ItemTemplate> </asp:TemplateField> </Columns> Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged Dim Instance_ID As String Dim Seq_ID As String Dim Form_Code As String Dim PARMS As String Dim DestinationURL As String Dim DestinationParms As String 'fill text box's with values from selected row ' store values from selected row Dim seqID As String = CType(GridView1.SelectedRow.FindControl("hdnSeqID"), HiddenField).Value Dim formCode As String = CType(GridView1.SelectedRow.FindControl("hdnFormCode"), HiddenField).Value End Sub

    Read the article

  • How can I execute an insert with data from a repeater-generated form whose data source is SQL?

    - by Duke
    I'm storing multilingual data in a database whose model is language normalized (like this). For this particular problem the key for the table in question consists of a value entered by the user and a language from the language table. I'd like to dynamically generate a form with input fields for all available languages. The user inputs a key value then goes down a list of field sets filling out the information in each language. In this case there are two fields for every language, a name and a value (the value is language dependent.) I have all existing information displayed on the page with a gridview, below which I have a formview that is always in insert mode allowing the user to enter new data. Within the formview I have a repeater with an SQLDataSource that gets a list of available languages: <asp:Repeater ID="SessionLocaleRepeater" runat="server" DataSourceID="LocaleSQLDataSource" EnableViewState="false"> <ItemTemplate> <tr> <th scope="row"><%# DataBinder.Eval(Container.DataItem, "LocaleName") %></th> <td>Name:</td> <td><asp:TextBox ID="TextBox1" runat="server" Text="" /></td> <td>Number:</td> <td><asp:TextBox ID="TextBox2" runat="server" Text="" /></td> </tr> </ItemTemplate> </asp:Repeater> I figured that in order to insert this data I'd have to execute my sql server insert stored procedure for each item in the repeater; I am trying to use the formview inserting event. The problem is that the repeater isn't databound to the SQLDataSource until after the formview inserting event (inserting event is in PostBackEvent and databind is in PreRender), which means the controls and data are not available when the inserting event is fired. I tried databinding the repeater during the formview inserting event; the controls were available but the data was not. Would this have something to do with how/when the viewstate information is re-added to the controls? From what I've read, Viewstate is one of the first things to be restored. Given the order of events how can I get the data I need for the insert? I'm open to other solutions to creating dynamic input controls, but they will have to query the database to determine how many sets of controls to create.

    Read the article

  • How can I change the TreeView Icon into a folder icon?

    - by KDP
    I'm trying to change the icon of my TreeView in a folder icon. Also when it collapses it needs to have an opened folder icon. My treeview has databound items in it and the code is: <TreeView x:Name="TreeViewCategories" Grid.Row="0" Grid.Column="1" Height="610" HorizontalAlignment="Left" Margin="29,111,0,0" VerticalAlignment="Top" Width="315" BorderThickness="0" Background="Transparent" > <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Items}"> <TextBlock FontSize="20" Text="{Binding Name}" PreviewMouseDown="TextBlock_PreviewMouseDown"/> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> Also this is how I fill the treeview with items from XML (It's a snipped out of alot of code: private void LoadHospitalXML() { try { FileStream fs = new FileStream("ConfigOrgHospital.xml", FileMode.Open, FileAccess.Read); var xml = XmlReader.Create(fs); rootElement = ConvertHospitalData(xml); this.TreeViewCategories.ItemsSource = null; List<HospitalWrapper> li = new List<HospitalWrapper>(); var hosp = rootElement.Items.FirstOrDefault(); if (hosp != null) { foreach (var i in hosp.Hospital) { li.AddIfNotNull(CreateHospList(i)); } } this.TreeViewCategories.ItemsSource = li; } catch (Exception e) { MessageBox.Show(e.Message); } } private HospitalWrapper CreateHospList(object obj) { var newItem = new HospitalWrapper(); newItem.Context = obj; //Hospital Names// if (obj is HospitalDataHospitalsHospital) { var hosp = (HospitalDataHospitalsHospital)obj; //newItem.Title = "Hospitals"; newItem.Name = hosp.DefaultName; var tmp = new HospitalWrapper(); tmp.Name = "Sites"; tmp.IsTitle = true; if (hosp.Sites != null) foreach (var i in hosp.Sites) { tmp.Items.AddIfNotNull(CreateHospList(i)); } newItem.Items.Add(tmp); tmp = new HospitalWrapper(); tmp.Name = "Specialties"; tmp.IsTitle = true; if (hosp.Deps != null) foreach (var j in hosp.Deps) { tmp.Items.AddIfNotNull(CreateHospList(j)); } newItem.Items.Add(tmp); } }

    Read the article

  • Creating an AJAX Accordion Menu

    - by jaullo
    Introduction Ajax is a powerful addition to asp.net that provides new functionality in a simple and agile  way This post is dedicated to creating a menu with ajax accordion type. About the Control The basic idea of this control, is to provide a serie of panels and show and hide information inside these panels. The use is very simple, we have to set each panel inside accordion control and give to each panel a Header and of course, we have to set the content of each panel.  To use accordion control, u need the ajax control toolkit. know the basic propertyes of accordion control:  Before start developing an accordion control, we have to know the basic properties for this control Other accordion propertyes  FramesPerSecond - Number of frames per second used in the transition animations RequireOpenedPane - Prevent closing the currently opened pane when its header is clicked (which ensures one pane is always open). The default value is true. SuppressHeaderPostbacks - Prevent the client-side click handlers of elements inside a header from firing (this is especially useful when you want to include hyperlinks in your headers for accessibility) DataSource - The data source to use. DataBind() must be called. DataSourceID - The ID of the data source to use. DataMember - The member to bind to when using a DataSourceID  AJAX Accordion Control Extender DataSource  The Accordion Control extender of AJAX Control toolkit can also be used as DataBound control. You can bind the data retrieved from the database to the Accordion control. Accordion Control consists of properties such as DataSource and DataSourceID (we can se it above) that can be used to bind the data. HeaderTemplate can used to display the header or title for the pane generated by the Accordion control, a click on which will open or close the ContentTemplate generated by binding the data with Accordion extender. When DataSource is passed to the Accordion control, also use the DataBind method to bind the data. The Accordion control bound with data auto generates the expand/collapse panes along with their headers.  This code represents the basic steps to bind the Accordion to a Datasource Collapse Public Sub getCategories() Dim sqlConn As New SqlConnection(conString) sqlConn.Open() Dim sqlSelect As New SqlCommand("SELECT * FROM Categories", sqlConn) sqlSelect.CommandType = System.Data.CommandType.Text Dim sqlAdapter As New SqlDataAdapter(sqlSelect) Dim myDataset As New DataSet() sqlAdapter.Fill(myDataset) sqlConn.Close() Accordion1.DataSource = myDataset.Tables(0).DefaultView Accordion1.DataBind()End Sub Protected Sub Accordion1_ItemDataBound(sender As Object, _ e As AjaxControlToolkit.AccordionItemEventArgs) If e.ItemType = AjaxControlToolkit.AccordionItemType.Content Then Dim sqlConn As New SqlConnection(conString) sqlConn.Open() Dim sqlSelect As New SqlCommand("SELECT productName " & _ "FROM Products where categoryID = '" + _ DirectCast(e.AccordionItem.FindControl("txt_categoryID"),_ HiddenField).Value + "'", sqlConn) sqlSelect.CommandType = System.Data.CommandType.Text Dim sqlAdapter As New SqlDataAdapter(sqlSelect) Dim myDataset As New DataSet() sqlAdapter.Fill(myDataset) sqlConn.Close() Dim grd As New GridView() grd = DirectCast(e.AccordionItem.FindControl("GridView1"), GridView) grd.DataSource = myDataset grd.DataBind() End If End Sub In the above code, we made two things, first, we made a sql select to database to retrieve all data from categories table, this data will be used to set the header and columns of the accordion.  Collapse <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <ajaxToolkit:Accordion ID="Accordion1" runat="server" TransitionDuration="100" FramesPerSecond="200" FadeTransitions="true" RequireOpenedPane="false" OnItemDataBound="Accordion1_ItemDataBound" ContentCssClass="acc-content" HeaderCssClass="acc-header" HeaderSelectedCssClass="acc-selected"> <HeaderTemplate> <%#DataBinder.Eval(Container.DataItem,"categoryName") %> </HeaderTemplate> <ContentTemplate> <asp:HiddenField ID="txt_categoryID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"categoryID") %>' /> <asp:GridView ID="GridView1" runat="server" RowStyle-BackColor="#ededed" RowStyle-HorizontalAlign="Left" AutoGenerateColumns="false" GridLines="None" CellPadding="2" CellSpacing="2" Width="300px"> <Columns> <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Product Name" HeaderStyle-BackColor="#d1d1d1" HeaderStyle-ForeColor="#777777"> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem,"productName") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </ContentTemplate> </ajaxToolkit:Accordion>  Here, we use <%#DataBinder.Eval(Container.DataItem,"categoryName") %> to bind accordion header with categoryName, so we made on header for each element found on database.    Creating a basic accordion control As we know, to use any of the ajax components, there must be a registered ScriptManager on our site, which will be responsible for managing our controls. So the first thing we will do is create our script manager.     Collapse <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> Then we define our accordion  element and establish some basic properties:    Collapse <cc1:Accordion ID="AccordionCtrl" runat="server" SelectedIndex="0" HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" AutoSize="None" FadeTransitions="true" TransitionDuration="250" FramesPerSecond="40" For our work we must declare PANES accordion inside it, these breads will be responsible for contain information, links or information that we want to show.  Collapse <Panes> <cc1:AccordionPane ID="AccordionPane0" runat="server"> <Header>Matenimiento</Header> <Content> <li><a href="mypagina.aspx">My página de prueba</a></li> </Content> </cc1:AccordionPane> To end this work, we have to close all panels and our accordion Collapse </Panes> </cc1:Accordion> Finally complete our example should look like:  Collapse <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <cc1:Accordion ID="AccordionCtrl" runat="server" SelectedIndex="0" HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" AutoSize="None" FadeTransitions="true" TransitionDuration="250" FramesPerSecond="40"> <Panes> <cc1:AccordionPane ID="AccordionPane0" runat="server"> <Header>Matenimiento</Header> <Content> <li><a href="mypagina.aspx">My página de prueba</a></li> </Content> </cc1:AccordionPane> </Panes> </cc1:Accordion>

    Read the article

  • Adding proper THEAD sections to a GridView

    - by Rick Strahl
    I’m working on some legacy code for a customer today and dealing with a page that has my favorite ‘friend’ on it: A GridView control. The ASP.NET GridView control (and also the older DataGrid control) creates some pretty messed up HTML. One of the more annoying things it does is to generate all rows including the header into the page in the <tbody> section of the document rather than in a properly separated <thead> section. Here’s is typical GridView generated HTML output: <table class="tablesorter blackborder" cellspacing="0" rules="all" border="1" id="Table1" style="border-collapse:collapse;"> <tr> <th scope="col">Name</th> <th scope="col">Company</th> <th scope="col">Entered</th><th scope="col">Balance</th> </tr> <tr> <td>Frank Hobson</td><td>Hobson Inc.</td> <td>10/20/2010 12:00:00 AM</td><td>240.00</td> </tr> ... </table> Notice that all content – both the headers and the body of the table – are generated directly under the <table> tag and there’s no explicit use of <tbody> or <thead> (or <tfooter> for that matter). When the browser renders this the document some default settings kick in and the DOM tree turns into something like this: <table> <tbody> <tr> <-- header <tr> <—detail row <tr> <—detail row </tbody> </table> Now if you’re just rendering the Grid server side and you’re applying all your styles through CssClass assignments this isn’t much of a problem. However, if you want to style your grid more generically using hierarchical CSS selectors it gets a lot more tricky to format tables that don’t properly delineate headers and body content. Also many plug-ins and other JavaScript utilities that work on tables require a properly formed table layout, and many of these simple won’t work out of the box with a GridView. For example, one of the things I wanted to do for this app is use the jQuery TableSorter plug-in which – not surprisingly – requires to work of table headers in the DOM document. Out of the box, the TableSorter plug-in doesn’t work with GridView controls, because the lack of a <thead> section to work on. Luckily with a little help of some jQuery scripting there’s a real easy fix to this problem. Basically, if we know the GridView generated table has a header in it, code like the following will move the headers from <tbody> to <thead>: <script type="text/javascript"> $(document).ready(function () { // Fix up GridView to support THEAD tags $("#gvCustomers tbody").before("<thead><tr></tr></thead>"); $("#gvCustomers thead tr").append($("#gvCustomers th")); $("#gvCustomers tbody tr:first").remove(); $("#gvCustomers").tablesorter({ sortList: [[1, 0]] }); }); </script> And voila you have a table that now works with the TableSorter plug-in. If you use GridView’s a lot you might want something a little more generic so the following does the same thing but should work more generically on any GridView/DataGrid missing its <thead> tag: function fixGridView(tableEl) {            var jTbl = $(tableEl);         if(jTbl.find("tbody>tr>th").length > 0) {         jTbl.find("tbody").before("<thead><tr></tr></thead>");         jTbl.find("thead tr").append(jTbl.find("th"));         jTbl.find("tbody tr:first").remove();     } } which you can call like this: $(document).ready(function () { fixGridView( $("#gvCustomers") ); $("#gvCustomers").tablesorter({ sortList: [[1, 0]] }); }); Server Side THEAD Rendering [updated from comments 11/21/2010] Several commenters pointed out that you can also do this on the server side by using the GridView.HeaderRow.TableSection property to force rendering with a proper table header. I was unaware of this option actually – not exactly an easy one to discover. One issue here is that timing of this needs to happen during the databinding process so you need to use an event handler: this.gvCustomers.DataBound += (object o, EventArgs ev) => { gvCustomers.HeaderRow.TableSection = TableRowSection.TableHeader; }; this.gvCustomers.DataSource = custList; this.gvCustomers.DataBind(); You can apply the same logic for the FooterRow. It’s beyond me why this rendering mode isn’t the default for a GridView – why would you ever want to have a table that doesn’t use a THEAD section??? But I disgress :-) I don’t use GridViews much anymore – opting for more flexible approaches using ListViews or even plain code based views or other custom displays that allow more control over layout, but I still see a lot of old code that does use them old clunkers including my own :) (gulp) and this does make life a little bit easier especially if you’re working with any of the jQuery table related plug-ins that expect a proper table structure.© Rick Strahl, West Wind Technologies, 2005-2010Posted in ASP.NET  jQuery  

    Read the article

< Previous Page | 2 3 4 5 6 7  | Next Page >