Search Results

Search found 236 results on 10 pages for 'findcontrol'.

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

  • Asp controls Id generation inside repeater

    - by toraan
    I define some controls inside repeater itemtemplate, the problem is with the Id that are generated automatically. This is my page: <asp:Repeater ID="rptThreads" runat="server" onitemcreated="rptThreads_ItemCreated"> <HeaderTemplate> <table cellpadding="0px" cellspacing="0"> </HeaderTemplate> <ItemTemplate> <tr style="height:50px"> <td> <asp:PlaceHolder ID="plcItemTitle" runat="server"> <asp:Panel id="titleContainer" runat="server" style="position:absolute;"> <asp:HyperLink ID="lnkTitle" runat="server" style="float:left;padding-right:10px;" Text='<%# Container.DataItem%>'/> <asp:Panel id="pnlEditButtons" runat="server" Visible="false" style="vertical-align:middle;z-index:100;display:none;float:left;" > <asp:ImageButton ID="imgbtn1" runat="server" ImageUrl="~/Images/misc/edit.png" /> <asp:ImageButton ID="imgbtn2" runat="server" ImageUrl="~/Images/misc/Rename.png" /> </asp:Panel> </asp:Panel> </asp:PlaceHolder> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> Now I will try to describe the problem: code-behind: protected void Page_Load(object sender, EventArgs e) { int [] array = {1,2,3,4,5}; rptThreads.DataSource = array; rptThreads.DataBind(); } protected void rptThreads_ItemCreated(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Panel editButtonsPanel = e.Item.FindControl("pnlEditButtons") as Panel; editButtonsPanel.Visible = true; Panel containerPanel = e.Item.FindControl("titleContainer") as Panel; //Point of Interest!!!! containerPanel.Attributes.Add("onmouseover", "ShowEditButtons('" + editButtonsPanel.ClientID + "');"); } } If I run the page as is, the generated html will be the following (I show only the first 2 items): <table cellpadding="0px" cellspacing="0"> <tr style="height:50px"> <td> <div id="titleContainer" onmouseover="ShowEditButtons('pnlEditButtons');" style="position:absolute;"> <a id="lnkTitle" style="float:left;padding-right:10px;">1</a> <div id="pnlEditButtons" style="vertical-align:middle;z-index:100;display:none;float:left;"> <input type="image" name="imgbtn1" id="imgbtn1" src="Images/misc/edit.png" style="border-width:0px;" /> <input type="image" name="imgbtn2" id="imgbtn2" src="Images/misc/Rename.png" style="border-width:0px;" /> </div> </div> </td> </tr> <tr style="height:50px"> <td> <div id="titleContainer" onmouseover="ShowEditButtons('pnlEditButtons');" style="position:absolute;"> <a id="lnkTitle" style="float:left;padding-right:10px;">2</a> <div id="pnlEditButtons" style="vertical-align:middle;z-index:100;display:none;float:left;"> <input type="image" name="imgbtn1" id="imgbtn1" src="Images/misc/edit.png" style="border-width:0px;" /> <input type="image" name="imgbtn2" id="imgbtn2" src="Images/misc/Rename.png" style="border-width:0px;" /> </div> </div> </td> </tr> As you can see all divs get the SAME ID, THIS I DONT WANT!!! But If I omit this line form the ItemCreated event: containerPanel.Attributes.Add("onmouseover", "ShowEditButtons('" + editButtonsPanel.ClientID + "');"); The generated HTML will be the following: <table cellpadding="0px" cellspacing="0"> <tr style="height:50px"> <td> <div id="rptThreads_ctl01_titleContainer" style="position:absolute;"> <a id="rptThreads_ctl01_lnkTitle" style="float:left;padding-right:10px;">1</a> <div id="rptThreads_ctl01_pnlEditButtons" style="vertical-align:middle;z-index:100;display:none;float:left;"> <input type="image" name="rptThreads$ctl01$imgbtn1" id="rptThreads_ctl01_imgbtn1" src="Images/misc/edit.png" style="border-width:0px;" /> <input type="image" name="rptThreads$ctl01$imgbtn2" id="rptThreads_ctl01_imgbtn2" src="Images/misc/Rename.png" style="border-width:0px;" /> </div> </div> </td> </tr> <tr style="height:50px"> <td> <div id="rptThreads_ctl02_titleContainer" style="position:absolute;"> <a id="rptThreads_ctl02_lnkTitle" style="float:left;padding-right:10px;">2</a> <div id="rptThreads_ctl02_pnlEditButtons" style="vertical-align:middle;z-index:100;display:none;float:left;"> <input type="image" name="rptThreads$ctl02$imgbtn1" id="rptThreads_ctl02_imgbtn1" src="Images/misc/edit.png" style="border-width:0px;" /> <input type="image" name="rptThreads$ctl02$imgbtn2" id="rptThreads_ctl02_imgbtn2" src="Images/misc/Rename.png" style="border-width:0px;" /> </div> </div> </td> </tr> All divs get unique IDs, and this I do want My questions are: 1)why it happens? why this line of code messup the ids? 2)how can have the unique ID's and assign javascript in codebehind? I can add this on aspx (it will wotk and I will get unique ids): onmouseover='<%# "javascript:ShowEditButtons(\""+ Container.FindControl("pnlEditButtons").ClientID+ "\");" %>' But I must do it in codebehind because I need to set the javascript only if server validate some things.

    Read the article

  • How to uncheck header checkbox in GridView when sorting and paging?

    - by OutOFTouch
    Hi, I followed this article and it works great except when paging or sorting the HeaderCheckBox is still checked. How and where should this be unchecked? I think it would be best to uncheck it in the control itself, but I am not having any luck even getting a reference to it using this code: protected override void OnSorted(EventArgs e) { base.OnSorted(e); if (AutoGenerateCheckBoxColumn) { CheckBox cb = (CheckBox) HeaderRow.FindControl(String.Format(HeaderCheckBoxId, ClientID)); if(cb != null) { cb.Checked = false; } } } Thanks

    Read the article

  • How to make a link button visible after another button has been clicked in asp.net(vb) in button_c

    - by Parth
    How to make a link button visible after another button has been clicked in asp.net(vb) in button_click() it says error as "Object reference not set to an instance of an object." i've done this in my code Protected Sub InsertButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim receipt As LinkButton = FormView1.FindControl("LinkButton1") ' receipt.Enabled = "true" ' receipt.EnableTheming = "true" ' receipt.EnableViewState = "true" receipt.Visible = "true" End Sub

    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

  • ASP.NET Controls – CommunityServer Captcha ControlAdapter, a practical case

    - by nmgomes
    The ControlAdapter is available since .NET framework version 2.0 and his main goal is to adapt and customize a control render in order to achieve a specific behavior or layout. This customization is done without changing the base control. A ControlAdapter is commonly used to custom render for specific platforms like Mobile. In this particular case the ControlAdapter was used to add a specific behavior to a Control. In this  post I will use one adapter to add a Captcha to all WeblogPostCommentForm controls within pontonetpt.com CommunityServer instance. The Challenge The ControlAdapter complexity is usually associated with the complexity/structure of is base control. This case is precisely one of those since base control dynamically load his content (controls) thru several ITemplate. Those of you who already played with ITemplate knows that while it is an excellent option for control composition it also brings to the table a big issue: “Controls defined within a template are not available for manipulation until they are instantiated inside another control.” While analyzing the WeblogPostCommentForm control I found that he uses the ITemplate technique to compose it’s layout and unfortunately I also found that the template content vary from theme to theme. This could have been a problem but luckily WeblogPostCommentForm control template content always contains a submit button with a well known ID (at least I can assume that there are a well known set of IDs). Using this submit button as anchor it’s possible to add the Captcha controls in the correct place. Another important finding was that WeblogPostCommentForm control inherits from the WrappedFormBase control which is the base control for all CommunityServer input forms. Knowing this inheritance link the main goal has changed to became the creation of a base ControlAdapter that  could be extended and customized to allow adding Captcha to: post comments form contact form user creation form. And, with this mind set, I decided to used the following ControlAdapter base class signature :public abstract class WrappedFormBaseCaptchaAdapter<T> : ControlAdapter where T : WrappedFormBase { }Great, but there are still many to do … Captcha The Captcha will be assembled with: A dynamically generated image with a set of random numbers A TextBox control where the image number will be inserted A Validator control to validate whether TextBox numbers match the image numbers This is a common Captcha implementation, is not rocket science and don’t bring any additional problem. The main problem, as told before, is to find the correct anchor control to ensure a correct Captcha control injection. The anchor control can vary by: target control  theme Implementation To support this dynamic scenario I choose to use the following implementation:private List<string> _validAnchorIds = null; protected virtual List<string> ValidAnchorIds { get { if (this._validAnchorIds == null) { this._validAnchorIds = new List<string>(); this._validAnchorIds.Add("btnSubmit"); } return this._validAnchorIds; } } private Control GetAnchorControl(T wrapper) { if (this.ValidAnchorIds == null || this.ValidAnchorIds.Count == 0) { throw new ArgumentException("Cannot be null or empty", "validAnchorNames"); } var q = from anchorId in this.ValidAnchorIds let anchorControl = CSControlUtility.Instance().FindControl(wrapper, anchorId) where anchorControl != null select anchorControl; return q.FirstOrDefault(); } I can now, using the ValidAnchorIds property, configure a set of valid anchor control  Ids. The GetAnchorControl method searches for a valid anchor control within the set of valid control Ids. Here, some of you may question why to use a LINQ To Objects expression, but the important here is to notice the usage of CSControlUtility.Instance().FindControl CommunityServer method. I want to build on top of CommunityServer not to reinvent the wheel. Assuming that an anchor control was found, it’s now possible to inject the Captcha at the correct place. This not something new, we do this all the time when creating server controls or adding dynamic controls:protected sealed override void CreateChildControls() { base.CreateChildControls(); if (this.IsCaptchaRequired) { T wrapper = base.Control as T; if (wrapper != null) { Control anchorControl = GetAnchorControl(wrapper); if (anchorControl != null) { Panel phCaptcha = new Panel {CssClass = "CommonFormField", ID = "Captcha"}; int index = anchorControl.Parent.Controls.IndexOf(anchorControl); anchorControl.Parent.Controls.AddAt(index, phCaptcha); CaptchaConfiguration.DefaultProvider.AddCaptchaControls( phCaptcha, GetValidationGroup(wrapper, anchorControl)); } } } } Here you can see a new entity in action: a provider. This is a CaptchaProvider class instance and is only goal is to create the Captcha itself and do everything else is needed to ensure is correct operation.public abstract class CaptchaProvider : ProviderBase { public abstract void AddCaptchaControls(Panel captchaPanel, string validationGroup); } You can create your own specific CaptchaProvider class to use different Captcha strategies including the use of existing Captcha services  like ReCaptcha. Once the generic ControlAdapter was created became extremely easy to created a specific one. Here is the specific ControlAdapter for the WeblogPostCommentForm control:public class WeblogPostCommentFormCaptchaAdapter : WrappedFormBaseCaptchaAdapter<WrappedFormBase> { #region Overriden Methods protected override List<string> ValidAnchorIds { get { List<string> validAnchorNames = base.ValidAnchorIds; validAnchorNames.Add("CommentSubmit"); return validAnchorNames; } } protected override string DefaultValidationGroup { get { return "CreateCommentForm"; } } #endregion Overriden Methods } Configuration This is the magic step. Without changing the original pages and keeping the application original assemblies untouched we are going to add a new behavior to the CommunityServer application. To glue everything together you must follow this steps: Add the following configuration to default.browser file:<?xml version='1.0' encoding='utf-8'?> <browsers> <browser refID="Default"> <controlAdapters> <!-- Adapter for the WeblogPostCommentForm control in order to add the Captcha and prevent SPAM comments --> <adapter controlType="CommunityServer.Blogs.Controls.WeblogPostCommentForm" adapterType="NunoGomes.CommunityServer.Components.WeblogPostCommentFormCaptchaAdapter, NunoGomes.CommunityServer" /> </controlAdapters> </browser> </browsers> Add the following configuration to web.config file:<configuration> <configSections> <!-- New section for Captcha providers configuration --> <section name="communityServer.Captcha" type="NunoGomes.CommunityServer.Captcha.Configuration.CaptchaSection" /> </configSections> <!-- Configuring a simple Captcha provider --> <communityServer.Captcha defaultProvider="simpleCaptcha"> <providers> <add name="simpleCaptcha" type="NunoGomes.CommunityServer.Captcha.Providers.SimpleCaptchaProvider, NunoGomes.CommunityServer" imageUrl="~/captcha.ashx" enabled="true" passPhrase="_YourPassPhrase_" saltValue="_YourSaltValue_" hashAlgorithm="SHA1" passwordIterations="3" keySize="256" initVector="_YourInitVectorWithExactly_16_Bytes_" /> </providers> </communityServer.Captcha> <system.web> <httpHandlers> <!-- The Captcha Image handler used by the simple Captcha provider --> <add verb="GET" path="captcha.ashx" type="NunoGomes.CommunityServer.Captcha.Providers.SimpleCaptchaProviderImageHandler, NunoGomes.CommunityServer" /> </httpHandlers> </system.web> <system.webServer> <handlers accessPolicy="Read, Write, Script, Execute"> <!-- The Captcha Image handler used by the simple Captcha provider --> <add verb="GET" name="captcha" path="captcha.ashx" type="NunoGomes.CommunityServer.Captcha.Providers.SimpleCaptchaProviderImageHandler, NunoGomes.CommunityServer" /> </handlers> </system.webServer> </configuration> Conclusion Building a ControlAdapter can be complex but the reward is his ability to allows us, thru configuration changes, to modify an application render and/or behavior. You can see this ControlAdapter in action here and here (anonymous required). A complete solution is available in “CommunityServer Extensions” Codeplex project.

    Read the article

  • Finding Buried Controls

    - by Bunch
    This post is pretty specific to an issue I had but still has some ideas that could be applied in other scenarios. The problem I had was updating a few buttons so their Text values could be set in the code behind which had a method to grab the proper value from an external source. This was so that if the application needed to be installed by a customer using a language other than English or needed a different notation for the button's Text they could simply update the database. Most of the time this was no big deal. However I had one instance where the button was part of a control, the button had no set ID and that control was only found in a dll. So there was no markup to edit for the Button. Also updating the dll was not an option so I had to make the best of what I had to work with. In the cs file for the aspx file with the control on it I added the Page_LoadComplete. The problem button was within a GridView so I added a foreach to go through each GridViewRow and find the button I needed. Since I did not have an ID to work with besides a random ctl00$main$DllControl$gvStuff$ctl03$ctl05 using the GridView's FindControl was out. I ended up looping through each GridViewRow, then if a RowState equaled Edit loop through the Cells, each control in the Cell and check each control to see if it held a Panel that contained the button. If the control was a Panel I could then loop through the controls in the Panel, find the Button that had text of "Update" (that was the hard coded part) and change it using the method to return the proper value from the database. if (rowState.Contains("Edit")){  foreach (DataControlFieldCell rowCell in gvr.Cells)  {   foreach (Control ctrl in rowCell.Controls)   {    if (ctrl.GetType() == typeof(Panel))     {     foreach (Control childCtrl in ctrl.Controls)     {      if (childCtrl.GetType() == typeof(Button))      {       Button update = (Button)childCtrl;       if (update.Text == "Update")       {        update.Text = method to return the external value for the button's text;       }      }     }    }   }  }} Tags: ASP.Net, CSharp

    Read the article

  • C# DotNetNuke Module: GridVIew AutoGenerateEditButton is skipping over a field on update.

    - by AlexMax
    I have a GridView with an automatically generated Edit button. I wanted some customized behavior for the Image column, since I wanted it to be a drop down list of items as opposed to a simple input field, and I also wanted some nice "fallback" in case the value in the database didn't actually exist in the drop down list. With the code I have done so far, I have gotten the behavior I desire out of the Image field. The problem is that when i attempt to update that particular field, I get an error spit out back at me that it can't find a method to update the form with: ObjectDataSource 'objDataSource' could not find a non-generic method 'UpdateDiscovery' that has parameters: ModuleId, Visible, Position, Title, Link, ItemId. That's not good, because I DO have an UpdateDiscovery method. However, between Title and Link, there is supposed to be another param that belongs to the Image field, and it's not being passed. I realize that it's probably the update button doesn't know to pass that field, since it's a TemplateField and not a BoundField, and when I use Bind('image') as the selected value for the drop down list, it seems to update fine...but only as long as the field in the database when I try and edit the row actually exists, otherwise it bombs out and gives me an error about the value not existing in the drop down list. I have the following GridView defined: <asp:GridView ID="grdDiscoverys" runat="server" DataSourceID="objDataSource" EnableModelValidation="True" AutoGenerateColumns="false" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" DataKeyNames="ItemId" OnRowDataBound="cmdDiscovery_RowDataBound"> <Columns> <asp:BoundField DataField="ItemId" HeaderText="#" ReadOnly="true" /> <asp:BoundField DataField="Visible" HeaderText="Visible" /> <asp:BoundField DataField="Position" HeaderText="Position" /> <asp:TemplateField HeaderText="Image"> <ItemTemplate> <asp:Label ID="lblViewImage" runat="server" /> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlEditImage" runat="server" title="Image" DataValueField="Key" DataTextField="Value" /> </EditItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Title" HeaderText="Title" /> <asp:BoundField DataField="Link" HeaderText="Link" /> </Columns> </asp:GridView> The datasource that this is tied to: <asp:ObjectDataSource ID="objDataSource" runat="server" TypeName="MyCompany.Modules.Discovery.DiscoveryController" SelectMethod="GetDiscoverys" UpdateMethod="UpdateDiscovery" DeleteMethod="DeleteDiscovery"> <SelectParameters> <asp:QueryStringParameter Name="ModuleId" QueryStringField="mid" /> </SelectParameters> <UpdateParameters> <asp:QueryStringParameter Name="ModuleId" QueryStringField="mid" /> </UpdateParameters> <DeleteParameters> <asp:QueryStringParameter Name="ModuleId" QueryStringField="mid" /> </DeleteParameters> </asp:ObjectDataSource> The cmdDiscovery_RowDataBound method that gets called when the row's data is bound is the following C# code: protected void cmdDiscovery_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowIndex >= 0) { int intImage = ((DiscoveryInfo)e.Row.DataItem).Image; if (grdDiscoverys.EditIndex == -1) { // View Label lblViewImage = ((Label)e.Row.FindControl("lblViewImage")); if (GetFileDictionary().ContainsKey(intImage)) { lblViewImage.Text = GetFileDictionary()[intImage]; } else { lblViewImage.Text = "Missing Image"; } } else { // Edit DropDownList ddlEditImage = ((DropDownList)e.Row.FindControl("ddlEditImage")); ddlEditImage.DataSource = GetFileDictionary(); ddlEditImage.DataBind(); if (GetFileDictionary().ContainsKey(intImage)) { ddlEditImage.SelectedValue = intImage.ToString(); } } } } catch (Exception exc) { //Module failed to load Exceptions.ProcessModuleLoadException(this, exc); } } How do I make sure that the Image value in the drop down list is passed to the update function?

    Read the article

  • ASP.NET Podcast Show #148 - ASP.NET WebForms to build a Mobile Web Application

    - by Wallym
    Check the podcast site for the original url. This is the video and source code for an ASP.NET WebForms app that I wrote that is optimized for the iPhone and mobile environments.  Subscribe to everything. Subscribe to WMV. Subscribe to M4V for iPhone/iPad. Subscribe to MP3. Download WMV. Download M4V for iPhone/iPad. Download MP3. Link to iWebKit. Source Code: <%@ Page Title="MapSplore" Language="C#" MasterPageFile="iPhoneMaster.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AT_iPhone_Default" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="Content" Runat="Server" ClientIDMode="Static">    <asp:ScriptManager ID="sm" runat="server"         EnablePartialRendering="true" EnableHistory="false" EnableCdn="true" />    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>    <script  language="javascript"  type="text/javascript">    <!--    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);    function endRequestHandle(sender, Args) {        setupMapDiv();        setupPlaceIveBeen();    }    function setupPlaceIveBeen() {        var mapPlaceIveBeen = document.getElementById('divPlaceIveBeen');        if (mapPlaceIveBeen != null) {            var PlaceLat = document.getElementById('<%=hdPlaceIveBeenLatitude.ClientID %>').value;            var PlaceLon = document.getElementById('<%=hdPlaceIveBeenLongitude.ClientID %>').value;            var PlaceTitle = document.getElementById('<%=lblPlaceIveBeenName.ClientID %>').innerHTML;            var latlng = new google.maps.LatLng(PlaceLat, PlaceLon);            var myOptions = {                zoom: 14,                center: latlng,                mapTypeId: google.maps.MapTypeId.ROADMAP            };            var map = new google.maps.Map(mapPlaceIveBeen, myOptions);            var marker = new google.maps.Marker({                position: new google.maps.LatLng(PlaceLat, PlaceLon),                map: map,                title: PlaceTitle,                clickable: false            });        }    }    function setupMapDiv() {        var mapdiv = document.getElementById('divImHere');        if (mapdiv != null) {            var PlaceLat = document.getElementById('<%=hdPlaceLat.ClientID %>').value;            var PlaceLon = document.getElementById('<%=hdPlaceLon.ClientID %>').value;            var PlaceTitle = document.getElementById('<%=hdPlaceTitle.ClientID %>').value;            var latlng = new google.maps.LatLng(PlaceLat, PlaceLon);            var myOptions = {                zoom: 14,                center: latlng,                mapTypeId: google.maps.MapTypeId.ROADMAP            };            var map = new google.maps.Map(mapdiv, myOptions);            var marker = new google.maps.Marker({                position: new google.maps.LatLng(PlaceLat, PlaceLon),                map: map,                title: PlaceTitle,                clickable: false            });        }     }    -->    </script>    <asp:HiddenField ID="Latitude" runat="server" />    <asp:HiddenField ID="Longitude" runat="server" />    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js%22%3E%3C/script>    <script language="javascript" type="text/javascript">        $(document).ready(function () {            GetLocation();            setupMapDiv();            setupPlaceIveBeen();        });        function GetLocation() {            if (navigator.geolocation != null) {                navigator.geolocation.getCurrentPosition(getData);            }            else {                var mess = document.getElementById('<%=Message.ClientID %>');                mess.innerHTML = "Sorry, your browser does not support geolocation. " +                    "Try the latest version of Safari on the iPhone, Android browser, or the latest version of FireFox.";            }        }        function UpdateLocation_Click() {            GetLocation();        }        function getData(position) {            var latitude = position.coords.latitude;            var longitude = position.coords.longitude;            var hdLat = document.getElementById('<%=Latitude.ClientID %>');            var hdLon = document.getElementById('<%=Longitude.ClientID %>');            hdLat.value = latitude;            hdLon.value = longitude;        }    </script>    <asp:Label ID="Message" runat="server" />    <asp:UpdatePanel ID="upl" runat="server">        <ContentTemplate>    <asp:Panel ID="pnlStart" runat="server" Visible="true">    <div id="topbar">        <div id="title">MapSplore</div>    </div>    <div id="content">        <ul class="pageitem">            <li class="menu">                <asp:LinkButton ID="lbLocalDeals" runat="server" onclick="lbLocalDeals_Click">                <asp:Image ID="imLocalDeals" runat="server" ImageUrl="~/Images/ArtFavor_Money_Bag_Icon.png" Height="30" />                <span class="name">Local Deals.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbLocalPlaces" runat="server" onclick="lbLocalPlaces_Click">                <asp:Image ID="imLocalPlaces" runat="server" ImageUrl="~/Images/Andy_Houses_on_the_horizon_-_Starburst_remix.png" Height="30" />                <span class="name">Local Places.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbWhereIveBeen" runat="server" onclick="lbWhereIveBeen_Click">                <asp:Image ID="imImHere" runat="server" ImageUrl="~/Images/ryanlerch_flagpole.png" Height="30" />                <span class="name">I've been here.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbMyStats" runat="server">                <asp:Image ID="imMyStats" runat="server" ImageUrl="~/Images/Anonymous_Spreadsheet.png" Height="30" />                <span class="name">My Stats.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="menu">                <asp:LinkButton ID="lbAddAPlace" runat="server" onclick="lbAddAPlace_Click">                <asp:Image ID="imAddAPlace" runat="server" ImageUrl="~/Images/jean_victor_balin_add.png" Height="30" />                <span class="name">Add a Place.</span>                <span class="arrow"></span>                </asp:LinkButton>                </li>            <li class="button">                <input type="button" value="Update Your Current Location" onclick="UpdateLocation_Click()">                </li>        </ul>    </div>    </asp:Panel>    <div>    <asp:Panel ID="pnlCoupons" runat="server" Visible="false">        <div id="topbar">        <div id="title">MapSplore</div>        <div id="leftbutton">            <asp:LinkButton runat="server" Text="Return"                 ID="ReturnFromDeals" OnClick="ReturnFromDeals_Click" /></div></div>    <div class="content">    <asp:ListView ID="lvCoupons" runat="server">        <LayoutTemplate>            <ul class="pageitem" runat="server">                <asp:PlaceHolder ID="itemPlaceholder" runat="server" />            </ul>        </LayoutTemplate>        <ItemTemplate>            <li class="menu">                <asp:LinkButton ID="lbBusiness" runat="server" Text='<%#Eval("Place.Name") %>' OnClick="lbBusiness_Click">                    <span class="comment">                    <asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Place.Address1") %>' />                    <asp:Label ID="lblDis" runat="server" Text='<%# Convert.ToString(Convert.ToInt32(Eval("Place.Distance"))) + " meters" %>' CssClass="smallText" />                    <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />                    <asp:HiddenField ID="hdGeoPromotionId" runat="server" Value='<%#Eval("GeoPromotionId") %>' />                    </span>                    <span class="arrow"></span>                </asp:LinkButton></li></ItemTemplate></asp:ListView><asp:GridView ID="gvCoupons" runat="server" AutoGenerateColumns="false">            <HeaderStyle BackColor="Silver" />            <AlternatingRowStyle BackColor="Wheat" />            <Columns>                <asp:TemplateField AccessibleHeaderText="Business" HeaderText="Business">                    <ItemTemplate>                        <asp:Image ID="imPlaceType" runat="server" Text='<%#Eval("Type") %>' ImageUrl='<%#Eval("Image") %>' />                        <asp:LinkButton ID="lbBusiness" runat="server" Text='<%#Eval("Name") %>' OnClick="lbBusiness_Click" />                        <asp:LinkButton ID="lblAddress" runat="server" Text='<%#Eval("Address1") %>' CssClass="smallText" />                        <asp:Label ID="lblDis" runat="server" Text='<%# Convert.ToString(Convert.ToInt32(Eval("Distance"))) + " meters" %>' CssClass="smallText" />                        <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />                        <asp:HiddenField ID="hdGeoPromotionId" runat="server" Value='<%#Eval("GeoPromotionId") %>' />                        <asp:Label ID="lblInfo" runat="server" Visible="false" />                    </ItemTemplate>                </asp:TemplateField>            </Columns>        </asp:GridView>    </div>    </asp:Panel>    <asp:Panel ID="pnlPlaces" runat="server" Visible="false">    <div id="topbar">        <div id="title">            MapSplore</div><div id="leftbutton">            <asp:LinkButton runat="server" Text="Return"                 ID="ReturnFromPlaces" OnClick="ReturnFromPlaces_Click" /></div></div>        <div id="content">        <asp:ListView ID="lvPlaces" runat="server">            <LayoutTemplate>                <ul id="ulPlaces" class="pageitem" runat="server">                    <asp:PlaceHolder ID="itemPlaceholder" runat="server" />                    <li class="menu">                        <asp:LinkButton ID="lbNotListed" runat="server" CssClass="name"                            OnClick="lbNotListed_Click">                            Place not listed                            <span class="arrow"></span>                            </asp:LinkButton>                    </li>                </ul>            </LayoutTemplate>            <ItemTemplate>            <li class="menu">                <asp:LinkButton ID="lbImHere" runat="server" CssClass="name"                     OnClick="lbImHere_Click">                <%#DisplayName(Eval("Name")) %>&nbsp;                <%# Convert.ToString(Convert.ToInt32(Eval("Distance"))) + " meters" %>                <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />                <span class="arrow"></span>                </asp:LinkButton></li></ItemTemplate></asp:ListView>    </div>    </asp:Panel>    <asp:Panel ID="pnlImHereNow" runat="server" Visible="false">        <div id="topbar">        <div id="title">            MapSplore</div><div id="leftbutton">            <asp:LinkButton runat="server" Text="Places"                 ID="lbImHereNowReturn" OnClick="lbImHereNowReturn_Click" /></div></div>            <div id="rightbutton">            <asp:LinkButton runat="server" Text="Beginning"                ID="lbBackToBeginning" OnClick="lbBackToBeginning_Click" />            </div>        <div id="content">        <ul class="pageitem">        <asp:HiddenField ID="hdPlaceId" runat="server" />        <asp:HiddenField ID="hdPlaceLat" runat="server" />        <asp:HiddenField ID="hdPlaceLon" runat="server" />        <asp:HiddenField ID="hdPlaceTitle" runat="server" />        <asp:Button ID="btnImHereNow" runat="server"             Text="I'm here" OnClick="btnImHereNow_Click" />             <asp:Label ID="lblPlaceTitle" runat="server" /><br />        <asp:TextBox ID="txtWhatsHappening" runat="server" TextMode="MultiLine" Rows="2" style="width:300px" /><br />        <div id="divImHere" style="width:300px; height:300px"></div>        </div>        </ul>    </asp:Panel>    <asp:Panel runat="server" ID="pnlIveBeenHere" Visible="false">        <div id="topbar">        <div id="title">            Where I've been</div><div id="leftbutton">            <asp:LinkButton ID="lbIveBeenHereBack" runat="server" Text="Back" OnClick="lbIveBeenHereBack_Click" /></div></div>        <div id="content">        <asp:ListView ID="lvWhereIveBeen" runat="server">            <LayoutTemplate>                <ul id="ulWhereIveBeen" class="pageitem" runat="server">                    <asp:PlaceHolder ID="itemPlaceholder" runat="server" />                </ul>            </LayoutTemplate>            <ItemTemplate>            <li class="menu" runat="server">                <asp:LinkButton ID="lbPlaceIveBeen" runat="server" OnClick="lbPlaceIveBeen_Click" CssClass="name">                    <asp:Label ID="lblPlace" runat="server" Text='<%#Eval("PlaceName") %>' /> at                    <asp:Label ID="lblTime" runat="server" Text='<%#Eval("ATTime") %>' CssClass="content" />                    <asp:HiddenField ID="hdATID" runat="server" Value='<%#Eval("ATID") %>' />                    <span class="arrow"></span>                </asp:LinkButton>            </li>            </ItemTemplate>        </asp:ListView>        </div>        </asp:Panel>    <asp:Panel runat="server" ID="pnlPlaceIveBeen" Visible="false">        <div id="topbar">        <div id="title">            I've been here        </div>        <div id="leftbutton">            <asp:LinkButton ID="lbPlaceIveBeenBack" runat="server" Text="Back" OnClick="lbPlaceIveBeenBack_Click" />        </div>        <div id="rightbutton">            <asp:LinkButton ID="lbPlaceIveBeenBeginning" runat="server" Text="Beginning" OnClick="lbPlaceIveBeenBeginning_Click" />        </div>        </div>        <div id="content">            <ul class="pageitem">            <li>            <asp:HiddenField ID="hdPlaceIveBeenPlaceId" runat="server" />            <asp:HiddenField ID="hdPlaceIveBeenLatitude" runat="server" />            <asp:HiddenField ID="hdPlaceIveBeenLongitude" runat="server" />            <asp:Label ID="lblPlaceIveBeenName" runat="server" /><br />            <asp:Label ID="lblPlaceIveBeenAddress" runat="server" /><br />            <asp:Label ID="lblPlaceIveBeenCity" runat="server" />,             <asp:Label ID="lblPlaceIveBeenState" runat="server" />            <asp:Label ID="lblPlaceIveBeenZipCode" runat="server" /><br />            <asp:Label ID="lblPlaceIveBeenCountry" runat="server" /><br />            <div id="divPlaceIveBeen" style="width:300px; height:300px"></div>            </li>            </ul>        </div>                </asp:Panel>         <asp:Panel ID="pnlAddPlace" runat="server" Visible="false">                <div id="topbar"><div id="title">MapSplore</div><div id="leftbutton"><asp:LinkButton ID="lbAddPlaceReturn" runat="server" Text="Back" OnClick="lbAddPlaceReturn_Click" /></div><div id="rightnav"></div></div><div id="content">    <ul class="pageitem">        <li id="liPlaceAddMessage" runat="server" visible="false">        <asp:Label ID="PlaceAddMessage" runat="server" />        </li>        <li class="bigfield">        <asp:TextBox ID="txtPlaceName" runat="server" placeholder="Name of Establishment" />        </li>        <li class="bigfield">        <asp:TextBox ID="txtAddress1" runat="server" placeholder="Address 1" />        </li>        <li class="bigfield">        <asp:TextBox ID="txtCity" runat="server" placeholder="City" />        </li>        <li class="select">        <asp:DropDownList ID="ddlProvince" runat="server" placeholder="Select State" />          <span class="arrow"></span>              </li>        <li class="bigfield">        <asp:TextBox ID="txtZipCode" runat="server" placeholder="Zip Code" />        </li>        <li class="select">        <asp:DropDownList ID="ddlCountry" runat="server"             onselectedindexchanged="ddlCountry_SelectedIndexChanged" />        <span class="arrow"></span>        </li>        <li class="bigfield">        <asp:TextBox ID="txtPhoneNumber" runat="server" placeholder="Phone Number" />        </li>        <li class="checkbox">            <span class="name">You Here Now:</span> <asp:CheckBox ID="cbYouHereNow" runat="server" Checked="true" />        </li>        <li class="button">        <asp:Button ID="btnAdd" runat="server" Text="Add Place"             onclick="btnAdd_Click" />        </li>    </ul></div>        </asp:Panel>        <asp:Panel ID="pnlImHere" runat="server" Visible="false">            <asp:TextBox ID="txtImHere" runat="server"                 TextMode="MultiLine" Rows="3" Columns="40" /><br />            <asp:DropDownList ID="ddlPlace" runat="server" /><br />            <asp:Button ID="btnHere" runat="server" Text="Tell Everyone I'm Here"                 onclick="btnHere_Click" /><br />        </asp:Panel>     </div>    </ContentTemplate>    </asp:UpdatePanel> </asp:Content> Code Behind .cs file: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using LocationDataModel; public partial class AT_iPhone_Default : ViewStatePage{    private iPhoneDevice ipd;     protected void Page_Load(object sender, EventArgs e)    {        LocationDataEntities lde = new LocationDataEntities();        if (!Page.IsPostBack)        {            var Countries = from c in lde.Countries select c;            foreach (Country co in Countries)            {                ddlCountry.Items.Add(new ListItem(co.Name, co.CountryId.ToString()));            }            ddlCountry_SelectedIndexChanged(ddlCountry, null);            if (AppleIPhone.IsIPad())                ipd = iPhoneDevice.iPad;            if (AppleIPhone.IsIPhone())                ipd = iPhoneDevice.iPhone;            if (AppleIPhone.IsIPodTouch())                ipd = iPhoneDevice.iPodTouch;        }    }    protected void btnPlaces_Click(object sender, EventArgs e)    {    }    protected void btnAdd_Click(object sender, EventArgs e)    {        bool blImHere = cbYouHereNow.Checked;        string Place = txtPlaceName.Text,            Address1 = txtAddress1.Text,            City = txtCity.Text,            ZipCode = txtZipCode.Text,            PhoneNumber = txtPhoneNumber.Text,            ProvinceId = ddlProvince.SelectedItem.Value,            CountryId = ddlCountry.SelectedItem.Value;        int iProvinceId, iCountryId;        double dLatitude, dLongitude;        DataAccess da = new DataAccess();        if ((!String.IsNullOrEmpty(ProvinceId)) &&            (!String.IsNullOrEmpty(CountryId)))        {            iProvinceId = Convert.ToInt32(ProvinceId);            iCountryId = Convert.ToInt32(CountryId);            if (blImHere)            {                dLatitude = Convert.ToDouble(Latitude.Value);                dLongitude = Convert.ToDouble(Longitude.Value);                da.StorePlace(Place, Address1, String.Empty, City,                    iProvinceId, ZipCode, iCountryId, PhoneNumber,                    dLatitude, dLongitude);            }            else            {                da.StorePlace(Place, Address1, String.Empty, City,                    iProvinceId, ZipCode, iCountryId, PhoneNumber);            }            liPlaceAddMessage.Visible = true;            PlaceAddMessage.Text = "Awesome, your place has been added. Add Another!";            txtPlaceName.Text = String.Empty;            txtAddress1.Text = String.Empty;            txtCity.Text = String.Empty;            ddlProvince.SelectedIndex = -1;            txtZipCode.Text = String.Empty;            txtPhoneNumber.Text = String.Empty;        }        else        {            liPlaceAddMessage.Visible = true;            PlaceAddMessage.Text = "Please select a State and a Country.";        }    }    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)    {        string CountryId = ddlCountry.SelectedItem.Value;        if (!String.IsNullOrEmpty(CountryId))        {            int iCountryId = Convert.ToInt32(CountryId);            LocationDataModel.LocationDataEntities lde = new LocationDataModel.LocationDataEntities();            var prov = from p in lde.Provinces where p.CountryId == iCountryId                        orderby p.ProvinceName select p;                        ddlProvince.Items.Add(String.Empty);            foreach (Province pr in prov)            {                ddlProvince.Items.Add(new ListItem(pr.ProvinceName, pr.ProvinceId.ToString()));            }        }        else        {            ddlProvince.Items.Clear();        }    }    protected void btnImHere_Click(object sender, EventArgs e)    {        int i = 0;        DataAccess da = new DataAccess();        double Lat = Convert.ToDouble(Latitude.Value),            Lon = Convert.ToDouble(Longitude.Value);        List<Place> lp = da.NearByLocations(Lat, Lon);        foreach (Place p in lp)        {            ListItem li = new ListItem(p.Name, p.PlaceId.ToString());            if (i == 0)            {                li.Selected = true;            }            ddlPlace.Items.Add(li);            i++;        }        pnlAddPlace.Visible = false;        pnlImHere.Visible = true;    }    protected void lbImHere_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        ListViewItem lvi = (ListViewItem)(((LinkButton)sender).Parent);        HiddenField hd = (HiddenField)lvi.FindControl("hdPlaceId");        long PlaceId = Convert.ToInt64(hd.Value);        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        Place pl = da.GetPlace(PlaceId);        pnlImHereNow.Visible = true;        pnlPlaces.Visible = false;        hdPlaceId.Value = PlaceId.ToString();        hdPlaceLat.Value = pl.Latitude.ToString();        hdPlaceLon.Value = pl.Longitude.ToString();        hdPlaceTitle.Value = pl.Name;        lblPlaceTitle.Text = pl.Name;    }    protected void btnHere_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        string WhatsH = txtImHere.Text;        long PlaceId = Convert.ToInt64(ddlPlace.SelectedValue);        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        da.StoreUserAT(UserName, PlaceId, WhatsH,            dLatitude, dLongitude);    }    protected void btnLocalCoupons_Click(object sender, EventArgs e)    {        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();     }    protected void lbBusiness_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        GridViewRow gvr = (GridViewRow)(((LinkButton)sender).Parent.Parent);        HiddenField hd = (HiddenField)gvr.FindControl("hdPlaceId");        string sPlaceId = hd.Value;        Int64 PlaceId;        if (!String.IsNullOrEmpty(sPlaceId))        {            PlaceId = Convert.ToInt64(sPlaceId);        }    }    protected void lbLocalDeals_Click(object sender, EventArgs e)    {        double dLatitude = Convert.ToDouble(Latitude.Value);        double dLongitude = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        pnlCoupons.Visible = true;        pnlStart.Visible = false;        List<GeoPromotion> lgp = da.NearByDeals(dLatitude, dLongitude);        lvCoupons.DataSource = lgp;        lvCoupons.DataBind();    }    protected void lbLocalPlaces_Click(object sender, EventArgs e)    {        DataAccess da = new DataAccess();        double Lat = Convert.ToDouble(Latitude.Value);        double Lon = Convert.ToDouble(Longitude.Value);        List<LocationDataModel.Place> places = da.NearByLocations(Lat, Lon);        lvPlaces.DataSource = places;        lvPlaces.SelectedIndex = -1;        lvPlaces.DataBind();        pnlPlaces.Visible = true;        pnlStart.Visible = false;    }    protected void ReturnFromPlaces_Click(object sender, EventArgs e)    {        pnlPlaces.Visible = false;        pnlStart.Visible = true;    }    protected void ReturnFromDeals_Click(object sender, EventArgs e)    {        pnlCoupons.Visible = false;        pnlStart.Visible = true;    }    protected void btnImHereNow_Click(object sender, EventArgs e)    {        long PlaceId = Convert.ToInt32(hdPlaceId.Value);        string UserName = Membership.GetUser().UserName;        string WhatsHappening = txtWhatsHappening.Text;        double UserLat = Convert.ToDouble(Latitude.Value);        double UserLon = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        da.StoreUserAT(UserName, PlaceId, WhatsHappening,             UserLat, UserLon);    }    protected void lbImHereNowReturn_Click(object sender, EventArgs e)    {        pnlImHereNow.Visible = false;        pnlPlaces.Visible = true;    }    protected void lbBackToBeginning_Click(object sender, EventArgs e)    {        pnlStart.Visible = true;        pnlImHereNow.Visible = false;    }    protected void lbWhereIveBeen_Click(object sender, EventArgs e)    {        string UserName = Membership.GetUser().UserName;        pnlStart.Visible = false;        pnlIveBeenHere.Visible = true;        DataAccess da = new DataAccess();        lvWhereIveBeen.DataSource = da.UserATs(UserName, 0, 15);        lvWhereIveBeen.DataBind();    }    protected void lbIveBeenHereBack_Click(object sender, EventArgs e)    {        pnlIveBeenHere.Visible = false;        pnlStart.Visible = true;    }     protected void lbPlaceIveBeen_Click(object sender, EventArgs e)    {        LinkButton lb = (LinkButton)sender;        ListViewItem lvi = (ListViewItem)lb.Parent.Parent;        HiddenField hdATID = (HiddenField)lvi.FindControl("hdATID");        Int64 ATID = Convert.ToInt64(hdATID.Value);        DataAccess da = new DataAccess();        pnlIveBeenHere.Visible = false;        pnlPlaceIveBeen.Visible = true;        var plac = da.GetPlaceViaATID(ATID);        hdPlaceIveBeenPlaceId.Value = plac.PlaceId.ToString();        hdPlaceIveBeenLatitude.Value = plac.Latitude.ToString();        hdPlaceIveBeenLongitude.Value = plac.Longitude.ToString();        lblPlaceIveBeenName.Text = plac.Name;        lblPlaceIveBeenAddress.Text = plac.Address1;        lblPlaceIveBeenCity.Text = plac.City;        lblPlaceIveBeenState.Text = plac.Province.ProvinceName;        lblPlaceIveBeenZipCode.Text = plac.ZipCode;        lblPlaceIveBeenCountry.Text = plac.Country.Name;    }     protected void lbNotListed_Click(object sender, EventArgs e)    {        SetupAddPoint();        pnlPlaces.Visible = false;    }     protected void lbAddAPlace_Click(object sender, EventArgs e)    {        SetupAddPoint();    }     private void SetupAddPoint()    {        double lat = Convert.ToDouble(Latitude.Value);        double lon = Convert.ToDouble(Longitude.Value);        DataAccess da = new DataAccess();        var zip = da.WhereAmIAt(lat, lon);        if (zip.Count > 0)        {            var z0 = zip[0];            txtCity.Text = z0.City;            txtZipCode.Text = z0.ZipCode;            ddlProvince.ClearSelection();            if (z0.ProvinceId.HasValue == true)            {                foreach (ListItem li in ddlProvince.Items)                {                    if (li.Value == z0.ProvinceId.Value.ToString())                    {                        li.Selected = true;                        break;                    }                }            }        }        pnlAddPlace.Visible = true;        pnlStart.Visible = false;    }    protected void lbAddPlaceReturn_Click(object sender, EventArgs e)    {        pnlAddPlace.Visible = false;        pnlStart.Visible = true;        liPlaceAddMessage.Visible = false;        PlaceAddMessage.Text = String.Empty;    }    protected void lbPlaceIveBeenBack_Click(object sender, EventArgs e)    {        pnlIveBeenHere.Visible = true;        pnlPlaceIveBeen.Visible = false;            }    protected void lbPlaceIveBeenBeginning_Click(object sender, EventArgs e)    {        pnlPlaceIveBeen.Visible = false;        pnlStart.Visible = true;    }    protected string DisplayName(object val)    {        string strVal = Convert.ToString(val);         if (AppleIPhone.IsIPad())        {            ipd = iPhoneDevice.iPad;        }        if (AppleIPhone.IsIPhone())        {            ipd = iPhoneDevice.iPhone;        }        if (AppleIPhone.IsIPodTouch())        {            ipd = iPhoneDevice.iPodTouch;        }        return (iPhoneHelper.DisplayContentOnMenu(strVal, ipd));    }} iPhoneHelper.cs file: using System;using System.Collections.Generic;using System.Linq;using System.Web; public enum iPhoneDevice{    iPhone, iPodTouch, iPad}/// <summary>/// Summary description for iPhoneHelper/// </summary>/// public class iPhoneHelper{ public iPhoneHelper() {  //  // TODO: Add constructor logic here  // } // This code is stupid in retrospect. Use css to solve this problem      public static string DisplayContentOnMenu(string val, iPhoneDevice ipd)    {        string Return = val;        string Elipsis = "...";        int iPadMaxLength = 30;        int iPhoneMaxLength = 15;        if (ipd == iPhoneDevice.iPad)        {            if (Return.Length > iPadMaxLength)            {                Return = Return.Substring(0, iPadMaxLength - Elipsis.Length) + Elipsis;            }        }        else        {            if (Return.Length > iPhoneMaxLength)            {                Return = Return.Substring(0, iPhoneMaxLength - Elipsis.Length) + Elipsis;            }        }        return (Return);    }}  Source code for the ViewStatePage: using System;using System.Data;using System.Data.SqlClient;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls; /// <summary>/// Summary description for BasePage/// </summary>#region Base class for a page.public class ViewStatePage : System.Web.UI.Page{     PageStatePersisterToDatabase myPageStatePersister;        public ViewStatePage()        : base()    {        myPageStatePersister = new PageStatePersisterToDatabase(this);    }     protected override PageStatePersister PageStatePersister    {        get        {            return myPageStatePersister;        }    } }#endregion #region This class will override the page persistence to store page state in a database.public class PageStatePersisterToDatabase : PageStatePersister{    private string ViewStateKeyField = "__VIEWSTATE_KEY";    private string _exNoConnectionStringFound = "No Database Configuration information is in the web.config.";     public PageStatePersisterToDatabase(Page page)        : base(page)    {    }     public override void Load()    {         // Get the cache key from the web form data        System.Int64 key = Convert.ToInt64(Page.Request.Params[ViewStateKeyField]);         Pair state = this.LoadState(key);         // Abort if cache object is not of type Pair        if (state == null)            throw new ApplicationException("Missing valid " + ViewStateKeyField);         // Set view state and control state        ViewState = state.First;        ControlState = state.Second;    }     public override void Save()    {         // No processing needed if no states available        if (ViewState == null && ControlState != null)            return;         System.Int64 key;        IStateFormatter formatter = this.StateFormatter;        Pair statePair = new Pair(ViewState, ControlState);         // Serialize the statePair object to a string.        string serializedState = formatter.Serialize(statePair);         // Save the ViewState and get a unique identifier back.        key = SaveState(serializedState);         // Register hidden field to store cache key in        // Page.ClientScript does not work properly with Atlas.        //Page.ClientScript.RegisterHiddenField(ViewStateKeyField, key.ToString());        ScriptManager.RegisterHiddenField(this.Page, ViewStateKeyField, key.ToString());    }     private System.Int64 SaveState(string PageState)    {        System.Int64 i64Key = 0;        string strConn = String.Empty,            strProvider = String.Empty;         string strSql = "insert into tblPageState ( SerializedState ) values ( '" + SqlEscape(PageState) + "');select scope_identity();";        SqlConnection sqlCn;        SqlCommand sqlCm;        try        {            GetDBConnectionString(ref strConn, ref strProvider);            sqlCn = new SqlConnection(strConn);            sqlCm = new SqlCommand(strSql, sqlCn);            sqlCn.Open();            i64Key = Convert.ToInt64(sqlCm.ExecuteScalar());            if (sqlCn.State != ConnectionState.Closed)            {                sqlCn.Close();            }            sqlCn.Dispose();            sqlCm.Dispose();        }        finally        {            sqlCn = null;            sqlCm = null;        }        return i64Key;    }     private Pair LoadState(System.Int64 iKey)    {        string strConn = String.Empty,            strProvider = String.Empty,            SerializedState = String.Empty,            strMinutesInPast = GetMinutesInPastToDelete();        Pair PageState;        string strSql = "select SerializedState from tblPageState where tblPageStateID=" + iKey.ToString() + ";" +            "delete from tblPageState where DateUpdated<DateAdd(mi, " + strMinutesInPast + ", getdate());";        SqlConnection sqlCn;        SqlCommand sqlCm;        try        {            GetDBConnectionString(ref strConn, ref strProvider);            sqlCn = new SqlConnection(strConn);            sqlCm = new SqlCommand(strSql, sqlCn);             sqlCn.Open();            SerializedState = Convert.ToString(sqlCm.ExecuteScalar());            IStateFormatter formatter = this.StateFormatter;             if ((null == SerializedState) ||                (String.Empty == SerializedState))            {                throw (new ApplicationException("No ViewState records were returned."));            }             // Deserilize returns the Pair object that is serialized in            // the Save method.            PageState = (Pair)formatter.Deserialize(SerializedState);             if (sqlCn.State != ConnectionState.Closed)            {                sqlCn.Close();            }            sqlCn.Dispose();            sqlCm.Dispose();        }        finally        {            sqlCn = null;            sqlCm = null;        }        return PageState;    }     private string SqlEscape(string Val)    {        string ReturnVal = String.Empty;        if (null != Val)        {            ReturnVal = Val.Replace("'", "''");        }        return (ReturnVal);    }    private void GetDBConnectionString(ref string ConnectionStringValue, ref string ProviderNameValue)    {        if (System.Configuration.ConfigurationManager.ConnectionStrings.Count > 0)        {            ConnectionStringValue = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;            ProviderNameValue = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ProviderName;        }        else        {            throw new ConfigurationErrorsException(_exNoConnectionStringFound);        }    }    private string GetMinutesInPastToDelete()    {        string strReturn = "-60";        if (null != System.Configuration.ConfigurationManager.AppSettings["MinutesInPastToDeletePageState"])        {            strReturn = System.Configuration.ConfigurationManager.AppSettings["MinutesInPastToDeletePageState"].ToString();        }        return (strReturn);    }}#endregion AppleiPhone.cs file: using System;using System.Collections.Generic;using System.Linq;using System.Web; /// <summary>/// Summary description for AppleIPhone/// </summary>public class AppleIPhone{ public AppleIPhone() {  //  // TODO: Add constructor logic here  // }     static public bool IsIPhoneOS()    {        return (IsIPad() || IsIPhone() || IsIPodTouch());    }     static public bool IsIPhone()    {        return IsTest("iPhone");    }     static public bool IsIPodTouch()    {        return IsTest("iPod");    }     static public bool IsIPad()    {        return IsTest("iPad");    }     static private bool IsTest(string Agent)    {        bool bl = false;        string ua = HttpContext.Current.Request.UserAgent.ToLower();        try        {            bl = ua.Contains(Agent.ToLower());        }        catch { }        return (bl);        }} Master page .cs: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls; public partial class MasterPages_iPhoneMaster : System.Web.UI.MasterPage{    protected void Page_Load(object sender, EventArgs e)    {            HtmlHead head = Page.Header;            HtmlMeta meta = new HtmlMeta();            if (AppleIPhone.IsIPad() == true)            {                meta.Content = "width=400,user-scalable=no";                head.Controls.Add(meta);             }            else            {                meta.Content = "width=device-width, user-scalable=no";                meta.Attributes.Add("name", "viewport");            }            meta.Attributes.Add("name", "viewport");            head.Controls.Add(meta);            HtmlLink cssLink = new HtmlLink();            HtmlGenericControl script = new HtmlGenericControl("script");            script.Attributes.Add("type", "text/javascript");            script.Attributes.Add("src", ResolveUrl("~/Scripts/iWebKit/javascript/functions.js"));            head.Controls.Add(script);            cssLink.Attributes.Add("rel", "stylesheet");            cssLink.Attributes.Add("href", ResolveUrl("~/Scripts/iWebKit/css/style.css") );            cssLink.Attributes.Add("type", "text/css");            head.Controls.Add(cssLink);            HtmlGenericControl jsLink = new HtmlGenericControl("script");            //jsLink.Attributes.Add("type", "text/javascript");            //jsLink.Attributes.Add("src", ResolveUrl("~/Scripts/jquery-1.4.1.min.js") );            //head.Controls.Add(jsLink);            HtmlLink appleIcon = new HtmlLink();            appleIcon.Attributes.Add("rel", "apple-touch-icon");            appleIcon.Attributes.Add("href", ResolveUrl("~/apple-touch-icon.png"));            HtmlMeta appleMobileWebAppStatusBarStyle = new HtmlMeta();            appleMobileWebAppStatusBarStyle.Attributes.Add("name", "apple-mobile-web-app-status-bar-style");            appleMobileWebAppStatusBarStyle.Attributes.Add("content", "black");            head.Controls.Add(appleMobileWebAppStatusBarStyle);    }     internal string FindPath(string Location)    {        string Url = Server.MapPath(Location);        return (Url);    }}

    Read the article

  • UpdatePanel, Repeater, DataBinding Problem

    - by Gordon Carpenter-Thompson
    In a user control, I've got a Repeater inside of an UpdatePanel (which id displayed inside of a ModalPopupExtender. The Repeater is databound using an array list of MyDTO objects. There are two buttons for each Item in the list. Upon binding the ImageURL and CommandArgument are set. This code works fine the first time around but the CommandArgument is wrong thereafter. It seems like the display is updated correctly but the DTO isn't and the CommandArgument sent is the one that has just been removed. Can anybody spot any problems with the code? ASCX <asp:UpdatePanel ID="ViewDataDetail" runat="server" ChildrenAsTriggers="true"> <Triggers> <asp:PostBackTrigger ControlID="ViewDataCloseButton" /> <asp:AsyncPostBackTrigger ControlID="DataRepeater" /> </Triggers> <ContentTemplate> <table width="100%" id="DataResults"> <asp:Repeater ID="DataRepeater" runat="server" OnItemCommand="DataRepeater_ItemCommand" OnItemDataBound="DataRepeater_ItemDataBound"> <HeaderTemplate> <tr> <th><b>Name</b></th> <th><b>&nbsp;</b></th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <b><%#((MyDTO)Container.DataItem).Name%></b> </td> <td> <asp:ImageButton CausesValidation="false" ID="DeleteData" CommandName="Delete" runat="server" /> <asp:ImageButton CausesValidation="false" ID="RunData" CommandName="Run" runat="server" /> </td> </tr> <tr> <td colspan="2"> <table> <tr> <td>Description : </td> <td><%#((MyDTO)Container.DataItem).Description%></td> </tr> <tr> <td>Search Text : </td> <td><%#((MyDTO)Container.DataItem).Text%></td> </tr> </table> </td> </tr> </ItemTemplate> </asp:Repeater> </table> </ContentTemplate> </asp:UpdatePanel> Code-Behind public DeleteData DeleteDataDelegate; public RetrieveData PopulateDataDelegate; public delegate ArrayList RetrieveData(); public delegate void DeleteData(String sData); protected void Page_Load(object sender, EventArgs e) { //load the initial data.. if (!Page.IsPostBack) { if (PopulateDataDelegate != null) { this.DataRepeater.DataSource = this.PopulateDataDelegate(); this.DataRepeater.DataBind(); } } } protected void DataRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "Delete") { if (DeleteDataDelegate != null) { DeleteDataDelegate((String)e.CommandArgument); BindDataToRepeater(); } } else if (e.CommandName == "Run") { String sRunning = (String)e.CommandArgument; this.ViewDataModalPopupExtender.Hide(); } } protected void DataRepeater_ItemDataBound(object source, RepeaterItemEventArgs e) { RepeaterItem item = e.Item; if (item != null && item.DataItem != null) { MyDTO oQuery = (MyDTO)item.DataItem; ImageButton oDeleteControl = (ImageButton) item.FindControl("DeleteData"); ImageButton oRunControl = (ImageButton)item.FindControl("RunData"); if (oDeleteControl != null && oRunControl !=null) { oRunControl.ImageUrl = "button_expand.gif"; oRunControl.CommandArgument = "MyID"; oDeleteControl.ImageUrl = "btn_remove.gif"; oDeleteControl.CommandArgument = "MyID"; } } } public void BindDataToRepeater() { this.DataRepeater.DataSource = this.PopulateDataDelegate(); this.DataRepeater.DataBind(); } public void ShowModal(object sender, EventArgs e) { BindDataToRepeater(); this.ViewDataModalPopupExtender.Show(); }

    Read the article

  • GridView_RowsDeleting event doesn't work

    - by iTayb
    I have a datagarid with a onrowdeleting="SellersGridView_RowsDeleting" switch. My method is: protected void SellersGridView_RowsDeleting(object sender, GridViewDeleteEventArgs e) { string seller = ((Label)SellersGridView.Rows[e.RowIndex].Cells[0].FindControl("TextBoxSeller")).Text; BookStore b = new BookStore(); b.LoadFromXML(Server.MapPath("list.xml")); string ISBN = Request.QueryString["ISBN"].ToString(); int ID = b.BooksList.FindIndex(x => x.ISBN == ISBN); Book myBook = b.BooksList[ID]; myBook.RemoveSeller(seller); Response.Redirect("editbook.aspx?ISBN=" + ISBN); } Well, it seems that when I try to delete anything - nothing happens. I tried to change the first line to Response.Redirect("foo") just to check if the event itself is fired, and it turns out that it doesn't. I can't get The reason. Here is my gridview control: http://pastebin.com/CKDAMECT Thank you very much!

    Read the article

  • Dictionary<string,string> to Dictionary<Control,object> using IEnumerable<T>.Select()

    - by abatishchev
    I have a System.Collections.Generic.Dictionary<string, string> containing control ID and appropriate data column to data bind: var dic = new Dictionary<string, string> { { "Label1", "FooCount" }, { "Label2", "BarCount" } }; I use it that way: var row = ((DataRowView)FormView1.DataItem).Row; Dictionary<Control, object> newOne = dic.ToDictionary( k => FormView1.FindControl(k.Key)), k => row[k.Value]); So I'm using IEnumerable<T>.ToDictionary(Func<T>, Func<T>). Is it possbile to do the same using IEnumerable<T>.Select(Func<T>) ?

    Read the article

  • Saving State Dynamic UserControls...Help!

    - by Cognitronic
    I have page with a LinkButton on it that when clicked, I'd like to add a Usercontrol to the page. I need to be able to add/remove as many controls as the user would like. The Usercontrol consists of three dropdownlists. The first dropdownlist has it's auotpostback property set to true and hooks up the OnSelectedIndexChanged event that when fired will load the remaining two dropdownlists with the appropriate values. My problem is that no matter where I put the code in the host page, the usercontrol is not being loaded properly. I know I have to recreate the usercontrols on every postback and I've created a method that is being executed in the hosting pages OnPreInit method. I'm still getting the following error: The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases. Here is my code: Thank you!!!! bool createAgain = false; IList<FilterOptionsCollectionView> OptionControls { get { if (SessionManager.Current["controls"] != null) return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"]; else SessionManager.Current["controls"] = new List<FilterOptionsCollectionView>(); return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"]; } set { SessionManager.Current["controls"] = value; } } protected void Page_Load(object sender, EventArgs e) { Master.Page.Title = Title; LoadViewControls(Master.MainContent, Master.SideBar, Master.ToolBarContainer); } protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); System.Web.UI.MasterPage m = Master; Control control = GetPostBackControl(this); if ((control != null && control.ClientID == (lbAddAndCondtion.ClientID) || createAgain)) { createAgain = true; CreateUserControl(control.ID); } } protected void AddAndConditionClicked(object o, EventArgs e) { var control = LoadControl("~/Views/FilterOptionsCollectionView.ascx"); OptionControls.Add((FilterOptionsCollectionView)control); control.ID = "options" + OptionControls.Count.ToString(); phConditions.Controls.Add(control); } public event EventHandler<Insight.Presenters.PageViewArg> OnLoadData; private Control FindControlRecursive(Control root, string id) { if (root.ID == id) { return root; } foreach (Control c in root.Controls) { Control t = FindControlRecursive(c, id); if (t != null) { return t; } } return null; } protected Control GetPostBackControl(System.Web.UI.Page page) { Control control = null; string ctrlname = Page.Request.Params["__EVENTTARGET"]; if (ctrlname != null && ctrlname != String.Empty) { control = FindControlRecursive(page, ctrlname.Split('$')[2]); } else { string ctrlStr = String.Empty; Control c = null; foreach (string ctl in Page.Request.Form) { if (ctl.EndsWith(".x") || ctl.EndsWith(".y")) { ctrlStr = ctl.Substring(0, ctl.Length - 2); c = page.FindControl(ctrlStr); } else { c = page.FindControl(ctl); } if (c is System.Web.UI.WebControls.CheckBox || c is System.Web.UI.WebControls.CheckBoxList) { control = c; break; } } } return control; } protected void CreateUserControl(string controlID) { try { if (createAgain && phConditions != null) { if (OptionControls.Count > 0) { phConditions.Controls.Clear(); foreach (var c in OptionControls) { phConditions.Controls.Add(c); } } } } catch (Exception ex) { throw ex; } } Here is the usercontrol's code: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FilterOptionsCollectionView.ascx.cs" Inherits="Insight.Website.Views.FilterOptionsCollectionView" %> namespace Insight.Website.Views { [ViewStateModeById] public partial class FilterOptionsCollectionView : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } protected override void OnInit(EventArgs e) { LoadColumns(); ddlColumns.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(ColumnsSelectedIndexChanged); base.OnInit(e); } protected void ColumnsSelectedIndexChanged(object o, EventArgs e) { LoadCriteria(); } public void LoadColumns() { ddlColumns.DataSource = User.GetItemSearchProperties(); ddlColumns.DataTextField = "SearchColumn"; ddlColumns.DataValueField = "CriteriaSearchControlType"; ddlColumns.DataBind(); LoadCriteria(); } private void LoadCriteria() { var controlType = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].CriteriaSearchControlType; var ops = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].ValidOperators; ddlOperators.DataSource = ops; ddlOperators.DataTextField = "key"; ddlOperators.DataValueField = "value"; ddlOperators.DataBind(); switch (controlType) { case ResourceStrings.ViewFilter_ControlTypes_DDL: criteriaDDL.Visible = true; criteriaText.Visible = false; var crit = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].SearchCriteria; ddlCriteria.DataSource = crit; ddlCriteria.DataBind(); break; case ResourceStrings.ViewFilter_ControlTypes_Text: criteriaDDL.Visible = false; criteriaText.Visible = true; break; } } public event EventHandler OnColumnChanged; public ISearchCriterion FilterOptionsValues { get; set; } } }

    Read the article

  • Accessing unbound DetailsView cell values when Detailsview DefaultMode is Edit

    - by Nickson
    i have a DetailsView that is populated by a Linq to Entities query. Example query is below. Dim Record = From L In db.MyRecords _ Where L.RecordID = 100 _ Select ID = L.RecordID, L.column1, L.column2, L.column3, L.column4 DetailsView2.DataSource = Record DetailsView2.DataBind() The defaultMode for the DetailsView is Edit. Now if this Detailsview was bound to a datasource control, i would convert a column to a templateColumn and programatically access cell values like so Dim NameTextBox As System.Web.UI.WebControls.TextBox = CType(DetailsView2.Rows(1).Cells(1).FindControl("TextBox1"), System.Web.UI.WebControls.TextBox) such that i can then say NameTextBox.Text to get the Name value. But the problem i have is, with this detailsview which is unbound, i have no column at design time to convert to a template, and yet i want to access its cell values. help is appreciated.

    Read the article

  • RowsDeleting event doesn't fire

    - by iTayb
    I have a gridview with a onrowdeleting="SellersGridView_RowsDeleting" switch. My method is: protected void SellersGridView_RowsDeleting(object sender, GridViewDeleteEventArgs e) { string seller = ((Label)SellersGridView.Rows[e.RowIndex].Cells[0].FindControl("TextBoxSeller")).Text; BookStore b = new BookStore(); b.LoadFromXML(Server.MapPath("list.xml")); string ISBN = Request.QueryString["ISBN"].ToString(); int ID = b.BooksList.FindIndex(x => x.ISBN == ISBN); Book myBook = b.BooksList[ID]; myBook.RemoveSeller(seller); Response.Redirect("editbook.aspx?ISBN=" + ISBN); } Well, it seems that when I try to delete anything - nothing happens. I tried to change the first line to Response.Redirect("foo") just to check if the event itself is fired, and it turns out that it doesn't. I can't get The reason. Here is my gridview control: http://pastebin.com/CKDAMECT Here is my codebehind code: http://pastebin.com/ShBtwGEu Thank you very much!

    Read the article

  • SP Gridview link button column not working

    - by Dilse Naaz
    Hi I have one sharepoint custom page application which is rendering from a user control. In the user control page, i had used SPGridview for displaying data. My first column is Title Column (link button column), when the user click on the link, then one popup window will open with corresponding data. But the problem is the link button is not working properly. But this application is working as fine in asp.net application. My code is shown below.. <asp:UpdatePanel runat="server" ID="UpdatePanel2"> <ContentTemplate> <SharePoint:SPGridView ID="dgApplicationBox" CellPadding="0" Height="100%" runat="server" ForeColor="Black" Font-Size="10px" Font-Names="Verdana" AutoGenerateColumns="False" AllowPaging="True" Width="100%" BorderStyle="None" BorderWidth="0px" PageSize="10" BorderColor="White" BackColor="White" OnRowDataBound="dgApplicationBox_RowDataBound" DataKeyNames="ApplicationID" OnSelectedIndexChanged="dgApplicationBox_SelectedIndexChanged" OnPageIndexChanging="dgApplicationBox_PageIndexChanging" CssClass="ms-listviewtable" AlternatingRowStyle-CssClass="ms-alternating"> <SelectedRowStyle Font-Bold="True" ForeColor="Black" BackColor="#CE5D5A"></SelectedRowStyle> <EditRowStyle Font-Size="10px" Font-Names="Verdana,Arial,Helvetica,sans-serif"></EditRowStyle> <HeaderStyle Font-Size="11px" Height="20px" Font-Bold="True" ForeColor="Black" BackColor="#E7E8EC"> </HeaderStyle> <PagerStyle HorizontalAlign="Center" ForeColor="#414E61" Font-Size="5px" Font-Names="arial" Height="10px" BackColor="#EBF3FF"></PagerStyle> <RowStyle /> <Columns> <asp:TemplateField HeaderText="Title" HeaderStyle-CssClass="ms-vb"> <ItemTemplate> <asp:LinkButton ID="lbtnSubject" Text='<%# Bind("UDF5") %>' runat="server" OnClick="lbtnSubject_Click"></asp:LinkButton> </ItemTemplate> <HeaderStyle HorizontalAlign="Left" CssClass="ms-vh2" Font-Bold="true" /> <ItemStyle HorizontalAlign="Left" CssClass="ms-vb2" /> </asp:TemplateField> <asp:TemplateField HeaderText="Request No."> <ItemTemplate> <asp:Label ID="lblReqNo" Text='<%# Bind("UDF1") %>' runat="server" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Left" CssClass="ms-vh2" Font-Bold="true" /> <ItemStyle HorizontalAlign="Left" CssClass="ms-vb2" /> </asp:TemplateField> <asp:BoundField DataField="CreatedOn" HeaderText="Created On" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"> <HeaderStyle CssClass="ms-vh2" Font-Bold="true"></HeaderStyle> <ItemStyle CssClass="ms-vb2"></ItemStyle> </asp:BoundField> <asp:BoundField DataField="Name" HeaderText="Form Type" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"> <HeaderStyle CssClass="ms-vh2" Font-Bold="true"></HeaderStyle> <ItemStyle CssClass="ms-vb2"></ItemStyle> </asp:BoundField> <asp:TemplateField HeaderText="History"> <HeaderStyle CssClass="ms-vh2" Font-Bold="true"></HeaderStyle> <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="21px" CssClass="ms-vb2"> </ItemStyle> <ItemTemplate> <asp:LinkButton ID="lbtnView" runat="server" OnClick="lbtnView_Click" >View</asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Application Id" Visible="False"> <ItemTemplate> <asp:Label ID="lblApplicationId" runat="server" Text='<%# Bind("ApplicationId") %>'></asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left" CssClass="ms-vh2" Font-Bold="true" /> <ItemStyle HorizontalAlign="Left" CssClass="ms-vb2" /> </asp:TemplateField> </Columns> </SharePoint:SPGridView> </ContentTemplate> </asp:UpdatePanel> when the user click on the link button, this code will works.. try { clearSession(); Session["DigitalSignature"] = null; Button btnDetails = sender as Button; DataTable dt = (DataTable)dgApplicationBox.DataSource; GridViewRow gvRow = (GridViewRow)(sender as LinkButton).Parent.Parent; Session["AppId"] = ((Label)gvRow.FindControl("lblApplicationId")).Text; string subject = ((LinkButton)gvRow.FindControl("lbtnSubject")).Text; WFInfo objWFInfo = new WFInfo(); objWFInfo.InitWorkflowProperty(Convert.ToInt32(Session["AppId"].ToString()), Session["CurrentUser"].ToString()); Session["FormId"] = objWFInfo.FormID.ToString(); string strFilname = objWFInfo.GetFormName(objWFInfo.ApplicationCategoryID.ToString()); string WindowName = strFilname; strFilname += ".aspx"; Session["CategoryId"] = objWFInfo.ApplicationCategoryID.ToString(); //pnlSubmitModal_ModalPopupExtender.Show(); ScriptManager.RegisterStartupScript(this, this.GetType(), "starScript", "popUpWindow('" + strFilname + "?tittle=" + subject + "', 800, 690,'" + WindowName + "');", true); this.Controls.Add(new LiteralControl("<script>alert('hi');</script>")); if (Session["CurrentUser"] != null) { ApplicationForm objApplication = new ApplicationForm(); objApplication.markRead(Convert.ToInt32(Session["AppId"].ToString()), Session["CurrentUser"].ToString()); } bindFolderData(); } If i click on the link button, there will be only post back occuring. but not the popup window open.. Please help me for resolving this problem. thanks in advance..

    Read the article

  • Improving code and UI Performance

    - by Kobojunkie
    I am dealing with a situation that I need some help with here. I need to improve performance on functionality that records and updates UI with user selection info. What my code current does is 'This is called to update the Database each time the user makes a new selection on the UI Private Sub OnFilterChanged(String newReviewValueToAdd) AddRecentViewToDB(newReviewValueToAdd) UpdateRecentViewsUI() PageReviewGrid.Rebind()'Call Grid Rebind End Sub 'This is the code that handles updating the UI with the Updated selection Private Sub UpdateRecentViewsUI() Dim rlNode As RadTreeNode = radTree.FindNodeByValue("myreviewnode") Dim Obj As Setting Dim treenode As RadTreeNode For i As Integer = 0 To Count - 1 Obj = Setting.Review.Item(i) treenode = New RadTreeNode(datetime.now.ToString,i.ToString()) treenode.ToolTip = obj.GetFilter radNode1.Nodes.Add(treenode) Next End Sub Private Sub UpdateRecentViewsUI() Dim pnlNav As RadPanelItem = rpbMyLoans.FindItemByValue("rpiMLNavTree") Dim radTree As RadTreeView = CType(pnlNav.FindControl("rtMyLoansNav"), RadTreeView) Dim rlNode As RadTreeNode = radTree.FindNodeByValue("MLRS") rlNode.Nodes.Clear() Dim objRS As SharedCode.WATSUserSettings.MyLoansView Dim objRTN As RadTreeNode For intItem As Integer = 0 To GetUserSettings.MyLoansRecentViews.Count - 1 objRS = GetUserSettings.MyLoansRecentViews.Item(intItem) objRTN = New RadTreeNode(objRS.LastUpdate.ToString, intItem.ToString) objRTN.ToolTip = objRS.getFilterString rlNode.Nodes.Add(objRTN) Next End Sub

    Read the article

  • Where does the ObjectDataSource cache data?

    - by Jeremy
    I'm considering using an ObjectDataSource as an intermediate between my page controls and my data access layer & object model. Traditionally I have manually created the object and populate it via a series of findcontrol statements when I need to insert/update data in the database. I'm hoping that I can use the ObjectDataSource to marshal data between my object and my controls, eliminating that manual code, as long as the ObjectDataSource doesn't come with a lot of overhead. I noticed the EnableCaching property, where does the caching occure? is it in view state?

    Read the article

  • Why doesnt the AsyncCallback update my gridview?

    - by Naruji
    Hi all, I started working with delegates last week and i am trying to update my gridview async on the background. All goes well, no errors or such but i dont get a result after my EndInvoke. does anyone know what i am doing wrong? Here is a code snippet: public delegate string WebServiceDelegate(DataKey key); protected void btnCheckAll_Click(object sender, EventArgs e) { foreach (DataKey key in gvTest.DataKeys) { WebServiceDelegate wsDelegate = new WebServiceDelegate(GetWebserviceStatus); wsDelegate.BeginInvoke(key, new AsyncCallback(UpdateWebserviceStatus), wsDelegate); } } public string GetWebserviceStatus(DataKey key) { return String.Format("Updated {0}", key.Value); } public void UpdateWebserviceStatus(IAsyncResult result) { WebServiceDelegate wsDelegate = (WebServiceDelegate)result.AsyncState; Label lblUpdate = (Label)gvTest.Rows[Convert.ToInt32(key.Value)].FindControl("lblUpdate"); lblUpdate.Text = wsDelegate.EndInvoke(result); }

    Read the article

  • How to change values of ListView elements in Codebehind

    - by Viredae
    Hello, I'm trying to create a table with Listview and one of the fields I'm using is supposed to show a hyperlink to a more detailed view of the data shown, how I want to do that is by using FindControl on the ID of that item and then changing the value into a hyperlink of the detailed view page with a querystring attached, the problem is that I have no idea how to re-insert that data back into the listview field, which looks something like this: <ItemTemplate> <td> <asp:Label ID="ViewLinkLabel" runat="server" Text='[insert Link Here]' /> </td> </ItemTemplate> Please bear in mind that I'm still an amateur in ASP.net, and if any of this seems too convoluted when there's a much easier to do this that I don't know about. Thank you

    Read the article

  • Set Dropdownlist value in listview on itemdatabound

    - by Samir
    hello, i have dropdownlist of year which is coming dynamically.i have filled the dropdownlist using object datasource.on inserting in the listview control it is working fine. but when i click on edit button that dropdownlist value should be set which is coming from the database. e.g. if i have a row which contains Year=2006 and month="Jan" then on click on edit button these dropdown list should be fill up. i have written the code in ItemDataBound to set the value of the dropdownlilst.but when i use findcontrol its taking null so object reference error is coming. so please provide me the solution. thanks samir

    Read the article

  • ASP.NET CompositeControl with child controls that contain children

    - by tomfanning
    I am building an ASP.NET server control which extends CompositeControl. I need fine grained control over the rendering, so I override Render() and output the child controls myself, interspersed with HTML generation code: writer.AddStyleAttribute("float", "left"); writer.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div); writer.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Strong); writer.Write("Table"); writer.RenderEndTag(); // strong writer.WriteBreak(); tableList.RenderControl(writer); writer.RenderEndTag(); // div This works really well for user controls that just contain simple controls without children of their own. However, if I want to use something like a MultiView or an UpdatePanel I run into problems, since I can't override Render() on View or UpdatePanel without extending them, and if I do extend them the implementation would presumably have to depend on FindControl() voodoo to get references to the right controls during render. That doesn't sound like the right way to do this - is there a better way?

    Read the article

  • Multi Select Checkbox using ListView

    - by Parsa
    I have a CheckBox in the header of ListView. I write a code to select all Checkboxes in ItemTemplate automatically when the user select the checkBox in the header of ListView. This code is useful, when you bind your ListView in DataPager_PreRender. protected void DataPager1_PreRender(object sender, EventArgs e) { //get the user id of the current user Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey; ListView1.DataSource = MyClass.MyStaticMethod(userGuid.ToString()); ListView1.DataBind(); } protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e) { //Find the checkBox in each Row CheckBox checkBoxRow = e.Item.FindControl("CheckBoxRow") as CheckBox; //Assign the value of checkBoxHeader to the checkBoxRow checkBoxRow.Checked = CheckBoxHeader.Checked; } protected void ListView1_PagePropertiesChanged(object sender, EventArgs e) { // assign false value to the CheckBoxHeader when user click on the DataPager // so if checkboxheader is true in the page 1, when user select Page 2,this check box will be false // therefore all checkbox rows will be false in the new page. if (CheckBoxHeader.Checked == true) CheckBoxHeader.Checked = false; }

    Read the article

  • Get control instance in asp.net dynamic data

    - by Ashwani K
    Hello All: I am creating a web application using Asp.net dynamic data. I am using GridView to show data from the database. In the grid view I am having following code for columns <Columns> <asp:DynamicField DataField="UserId" UIHint="Label" /> <asp:DynamicField DataField="Address" UIHint="Address"/> <asp:DynamicField DataField="CreatedDate" UIHint="Label" /> </Columns> But, before displaying I want to do some processing in C# code for each row. In normal ASP.net grid view we can handle OnRowDataBound method, and using FindControl("controlid") we can get the control instance, but in case of dynamic data, I am not getting any id attribute for columns, so I am not able to get the control instance to show updated data in that control depending on some conditions. Thanks, Ashwani

    Read the article

  • C# Nested Repeater Accessing elements

    - by Rich
    I have a list of Accommodation objects bound to a Repeater, and then a nested Repeater which has the various attendee groups listed [e.g. Default, Seniors, Juniors]. This is all output fine, with the values displayed as LinkButtons, which when clicked gets sent to a code-behind event handler. Here is an example of the output to give you a picture [with some er... interesting attendee group names]: In the event handler, I test the object parameter to see which Repeater has been sent, as the outer repeater's links can also be clicked [so the Accommodation would be set, but no Attendee Group]. Is there a way to get a HiddenField from the outer RepeaterItem that contains the currently clicked inner repeater's LinkButton? E.g. From the image, I click the Attending link in the Women section. So the EventArgs via FindControl can get me the hidden field which contains the Attendee Group's ID, which is good, but I also need the Accommodation ID [to know whether it was either Wimbledon Hotel Inn or New Acc]

    Read the article

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