Search Results

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

Page 10/10 | < Previous Page | 6 7 8 9 10 

  • ASP.NET Membership API not working on Win2008 server/IIS7

    - by Program.X
    I have a very odd problem. I have a web app that uses the .NET Membership API to provide login functionality. This works fine on my local dev machine, using WebDev 4.0 server. I'm using .NET 4.0 with some URL Rewriting, but not on the pages where login is required. I have a Windows Server 2008 with IIS7 However, the Membership API seemingly does not work on the server. I have set up remote debugging and the LoginUser.LoggedIn event of the LoginUser control gets fired okay, but the MembershipUser is null. I get no answer about the username/password being invalid so it seems to be recognising it. If I enter an invalid username/password, I get an invalid username/password response. Some code, if it helps: <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="validation-error-list" ValidationGroup="LoginUserValidationGroup"/> <div class="accountInfo"> <fieldset class="login"> <legend>Account Information</legend> <p> <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label> <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" CssClass="validation-error" Display="Dynamic" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label> <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" CssClass="validation-error" Display="Dynamic" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:CheckBox ID="RememberMe" runat="server"/> <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label> </p> </fieldset> <p class="login-action"> <asp:Button ID="LoginButton" runat="server" CommandName="Login" CssClass="submitButton" Text="Log In" ValidationGroup="LoginUserValidationGroup"/> </p> and the code behind: protected void Page_Load(object sender, EventArgs e) { LoginUser.LoginError += new EventHandler(LoginUser_LoginError); LoginUser.LoggedIn += new EventHandler(LoginUser_LoggedIn); } void LoginUser_LoggedIn(object sender, EventArgs e) { // this code gets run so it appears logins work Roles.DeleteCookie(); // this behaviour has been removed for testing - no difference } void LoginUser_LoginError(object sender, EventArgs e) { HtmlGenericControl htmlGenericControl = LoginUser.FindControl("errorMessageSpan") as HtmlGenericControl; if (htmlGenericControl != null) htmlGenericControl.Visible = true; } I have "Fiddled" with the Login form reponse and I get the following Cookie-Set headers: Set-Cookie: ASP.NET_SessionId=lpyyiyjw45jjtuav1gdu4jmg; path=/; HttpOnly Set-Cookie: .ASPXAUTH=A7AE08E071DD20872D6BBBAD9167A709DEE55B352283A7F91E1066FFB1529E5C61FCEDC86E558CEA1A837E79640BE88D1F65F14FA8434AA86407DA3AEED575E0649A1AC319752FBCD39B2A4669B0F869; path=/; HttpOnly Set-Cookie: .ASPXROLES=; expires=Mon, 11-Oct-1999 23:00:00 GMT; path=/; HttpOnly I don't know what is useful here because it is obviously encrypted but I find the .APXROLES cookie having no value interesting. It seems to fail to register the cookie, but passes authentication

    Read the article

  • LinkButtons Created Dynamically in a Repeater Don't Fire ItemCommand Event

    - by 5arx
    Hi. I've got a repeater that's used to display the output of a dynamic report that takes criteria from webcontrols on the page. Within the repeater's ItemDataBound method I'm adding controls (Linkbuttons for sorting by column values) dynamically to the header of the repeater based on values selected in a checkbox list and at this point setting the CommandArgument and CommandName properties of the linkbuttons. The issue is that when the linkbuttons are clicked they don't fire the ItemCommand event although they are clearly being correctly created and added to the header (there is some additional code to set the cssClass, text etc. and this works as expected.) The first column header in the repeater is set in the markup and the itemcommand event fires correctly on this one only. When the other column headers are clicked the repeater rebinds as programmed, but the columns are not dynamically re-generated. I would really appreciate somebody explaining what I'm doing wrong - afaik I'm following the approved way of doing this :-( Simplified code follows: Nightmare.ascx <asp:repeater runat="server" id="rptReport" OnItemDataBound="rptResults_ItemDataBound" OnItemCommand="rptResults_ItemCommand" EnableViewState="true"> <headertemplate> <table> <tr runat="Server" id="TRDynamicHeader"> <th> <!-- This one works --> <asp:Linkbutton runat="server" CommandName="sort" commandArgument='<%# Eval("Name")%?' /> </th> <!-- additional header cells get added dynamically here --> </tr> </headertemplate> <itemTemplate> <td><%# Eval("Name")</td> ... </itemTemplate> </asp:repeater> Nightmare.ascx.cs protected void PageLoad(object sender, eventArgs e){ if (! isPostback){ setupGui();//just binds dropdowns etc. to datasources } } protected void btnRunReport_Click(...){ List<ReportLines> lstRep = GetReportLines(); rptReport.DataSource = lstRep; repReport.DataBind(); } protected void rptReport_ItemDataBound (...){ if (e.Item.ItemType == ListItemType.Header) { foreach (ListItem li in chbxListBusFuncs.Items) { if (li.Selected) { th = new HtmlTableCell(); lb = new LinkButton(); lb.CssClass = "SortColHeader"; lb.CommandArgument = li.Text.Replace(" ", ""); lb.CommandName = "sort"; lb.Text = li.Text; th.Controls.Add(lb); ((HtmlTableRow)e.Item.FindControl("TRDynamicHeader")).Cells.Add(th); } } } if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { //Row level customisations, totals calculations etc. } } <!-- this only gets called when the 'hardcoded' linkbutton in the markup is clicked. protected void rptReport_ItemCommand(object sender, Eventargs e){ lblDebug.Text = string.Format("Well? What's Happening? -> {0}:{1}", e.CommandName, e.CommandArgument.ToString()); } (The only thing that can call the runreport routine is a single button on the page, not shown in the code snippet above.)

    Read the article

  • Hidden Field asp.net

    - by user329419
    I want to hide columns in asp.net in GridView then access the values in GridViewSelectIndexChanged using vb.net. I am using hidden fields in the GridView. When I try to access gives me an error object reference not set to an instance here is the code <asp:GridView ID="GridView1" runat="server" OnSorting="GridView1_OnSorting" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BorderStyle="Outset" CellPadding="4" DataSourceID="odsA02_Tracking" ForeColor="#333333" GridLines="Vertical" Style="border-right: #0000ff thin solid; table-layout: auto; border-top: #0000ff thin solid; font-size: x-small; border-left: #0000ff thin solid; border-bottom: #0000ff thin solid; font-family: Arial; border-collapse: separate" Font-Size="Small" PageSize="30"> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <RowStyle BackColor="#EFF3FB" /> <EditRowStyle BackColor="#2461BF" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:boundfield datafield="Since" HeaderText="Submit Date" ReadOnly=true SortExpression="Since" /> <asp:BoundField DataField="Started_By" HeaderText="Submitted By" SortExpression="Started_By" /> <asp:BoundField DataField="Client_FullName" HeaderText="Client Name" ReadOnly="True" SortExpression="Client_FullName" /> <asp:BoundField DataField="Product_Desc" HeaderText="Product" ReadOnly="True" SortExpression="Product_Desc" /> <asp:BoundField DataField="Branch_List" HeaderText="Branch" ReadOnly="True" SortExpression="Branch_List" /> <asp:BoundField DataField="Event_AssignedID" HeaderText="Assigned To" ReadOnly="True" SortExpression="Event_AssignedID" /> <asp:BoundField DataField="DaysElapsed" HeaderText="Days Open" ReadOnly="True" SortExpression="DaysElapsed" /> <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" /> <asp:TemplateField HeaderText=Instance_ID > <ItemTemplate> <asp:HiddenField ID=lblInstanceID Value='<%#Eval("Instance_ID") %>' runat=server> </asp:HiddenField> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText=Seq_ID> <ItemTemplate> <asp:HiddenField ID=lblSeqID Value='<%#Eval("Seq_ID") %>' runat=server/> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText=Form_Code> <ItemTemplate> <asp:HiddenField ID=lblFormCode Value='<%#Eval("Form_Code") %>' runat=server/> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged Dim Instance_ID As String Dim Seq_ID As String Dim Form_Code As String Dim PARMS As String Dim DestinationURL As String Dim DestinationParms As String Dim instanceID As String = CType(GridView1.FindControl("lblInstanceID"), HiddenField).Value End sub

    Read the article

  • SharePoint: Problem with BaseFieldControl

    - by Anoop
    Hi All, In below code in a Gird First column is BaseFieldControl from a column of type Choice of SPList. Secound column is a text box control with textchange event. Both the controls are created at rowdatabound event of gridview. Now the problem is that when Steps: 1) select any of the value from BaseFieldControl(DropDownList) which is rendered from Choice Column of SPList 2) enter any thing in textbox in another column of grid. 3) textchanged event fires up and in textchange event rebound the grid. Problem: the selected value becomes the first item or the default value(if any). but if i do not rebound the grid at text changed event it works fine. Please suggest what to do. using System; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace SharePointProjectTest.Layouts.SharePointProjectTest { public partial class TestBFC : LayoutsPageBase { GridView grid = null; protected void Page_Load(object sender, EventArgs e) { try { grid = new GridView(); grid.ShowFooter = true; grid.ShowHeader = true; grid.AutoGenerateColumns = true; grid.ID = "grdView"; grid.RowDataBound += new GridViewRowEventHandler(grid_RowDataBound); grid.Width = Unit.Pixel(900); MasterPage holder = (MasterPage)Page.Controls[0]; holder.FindControl("PlaceHolderMain").Controls.Add(grid); DataTable ds = new DataTable(); ds.Columns.Add("Choice"); //ds.Columns.Add("person"); ds.Columns.Add("Curr"); for (int i = 0; i < 3; i++) { DataRow dr = ds.NewRow(); ds.Rows.Add(dr); } grid.DataSource = ds; grid.DataBind(); } catch (Exception ex) { } } void tx_TextChanged(object sender, EventArgs e) { DataTable ds = new DataTable(); ds.Columns.Add("Choice"); ds.Columns.Add("Curr"); for (int i = 0; i < 3; i++) { DataRow dr = ds.NewRow(); ds.Rows.Add(dr); } grid.DataSource = ds; grid.DataBind(); } void grid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { SPWeb web = SPContext.Current.Web; SPList list = web.Lists["Source for test"]; SPField field = list.Fields["Choice"]; SPListItem item=list.Items.Add(); BaseFieldControl control = (BaseFieldControl)GetSharePointControls(field, list, item, SPControlMode.New); if (control != null) { e.Row.Cells[0].Controls.Add(control); } TextBox tx = new TextBox(); tx.AutoPostBack = true; tx.ID = "Curr"; tx.TextChanged += new EventHandler(tx_TextChanged); e.Row.Cells[1].Controls.Add(tx); } } public static Control GetSharePointControls(SPField field, SPList list, SPListItem item, SPControlMode mode) { if (field == null || field.FieldRenderingControl == null || field.Hidden) return null; try { BaseFieldControl webControl = field.FieldRenderingControl; webControl.ListId = list.ID; webControl.ItemId = item.ID; webControl.FieldName = field.Title; webControl.ID = "id_" + field.InternalName; webControl.ControlMode = mode; webControl.EnableViewState = true; return webControl; } catch (Exception ex) { return null; } } } }

    Read the article

  • Binding DataTable To GridView, But No Rows In GridViewRowCollection Despite GridView Population?

    - by KSwift87
    Problem: I've coded a GridView in the markup in a page. I have coded a DataTable in the code-behind that takes data from a collection of custom objects. I then bind that DataTable to the GridView. (Specific problem mentioned a couple code-snippets below.) GridView Markup: <asp:GridView ID="gvCart" runat="server" CssClass="pList" AutoGenerateColumns="false" DataKeyNames="ProductID"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" /> <asp:BoundField DataField="Name" HeaderText="ProductName" /> <asp:ImageField DataImageUrlField="Thumbnail" HeaderText="Thumbnail"></asp:ImageField> <asp:BoundField DataField="Unit Price" HeaderText="Unit Price" /> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox ID="Quantity" runat="server" Text="<%# Bind('Quantity') %>" Width="25px"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Total Price" HeaderText="Total Price" /> </Columns> </asp:GridView> DataTable Code-Behind: private void View(List<OrderItem> cart) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("Cart"); if (cart != null) { dt.Columns.Add("ProductID"); dt.Columns.Add("Name"); dt.Columns.Add("Thumbnail"); dt.Columns.Add("Unit Price"); dt.Columns.Add("Quantity"); dt.Columns.Add("Total Price"); foreach (OrderItem item in cart) { DataRow dr = dt.NewRow(); dr["ProductID"] = item.productId.ToString(); dr["Name"] = item.productName; dr["Thumbnail"] = ResolveUrl(item.productThumbnail); dr["Unit Price"] = "$" + item.productPrice.ToString(); dr["Quantity"] = item.productQuantity.ToString(); dr["Total Price"] = "$" + (item.productPrice * item.productQuantity).ToString(); dt.Rows.Add(dr); } gvCart.DataSource = dt; gvCart.DataBind(); gvCart.Width = 500; for (int counter = 0; counter < gvCart.Rows.Count; counter++) { gvCart.Rows[counter].Cells.Add(Common.createCell("<a href='cart.aspx?action=update&prodId=" + gvCart.Rows[counter].Cells[0].Text + "'>Update</a><br /><a href='cart.aspx?action='action=remove&prodId=" + gvCart.Rows[counter].Cells[0].Text + "/>Remove</a>")); } } } Error occurs below in the foreach - the GridViewRowCollection is empty! private void Update(string prodId) { List<OrderItem> cart = (List<OrderItem>)Session["cart"]; int uQty = 0; foreach (GridViewRow gvr in gvCart.Rows) { if (gvr.RowType == DataControlRowType.DataRow) { if (gvr.Cells[0].Text == prodId) { uQty = int.Parse(((TextBox)gvr.Cells[4].FindControl("Quantity")).Text); } } } Goal: I'm basically trying to find a way to update the data in my GridView (and more importantly my cart Session object) without having to do everything else I've seen online such as utilizing OnRowUpdate, etc. Could someone please tell me why gvCart.Rows is empty and/or how I could accomplish my goal without utilizing OnRowUpdate, etc.? When I execute this code, the GridView gets populated but for some reason I can't access any of its rows in the code-behind.

    Read the article

  • Editing a Gridview row with drop-down lists gets too wide - how can I use popup panels instead?

    - by David
    I have a series of GridViews in a Tab Panel - databound to a generic List of Business Objects. The columns in the Gridview are all similar to the following: <asp:TemplateField HeaderText="Company" SortExpression="Company.ShortName"> <ItemTemplate> <asp:Label ID="lblCompany" runat="server" Text='<%# Bind("Company.ShortName") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlCompany" runat="server"></asp:DropDownList> </EditItemTemplate> </asp:TemplateField> The GridView generates the "Edit" link at the beginning of the row, all the events fire ok. The problem is that the data is getting long. When in 'display mode', it's fine because the GridView control is smart enough to break some text into multiple lines (in particular Project, Title and Worker names can get pretty long). The problem come in editing mode. Drop-down lists DON'T break entries into multiple lines (for obvious reasons). Going into Edit ode on a row in the Gridview can make the Griview expand horizontally to twice the screen size (blowing through the width limits in the Master page and CSS but that's only a related problem). What I need is something like the ModalPopup - but trying to tie it to an ID in an EditItemTemplate gives me errors when the page renders (because the 'ddlXXXX' doesn't exist at the time). In addition I don't know how to dynamically populate the panel so that I can get a response from it (like the ID of the Company they selected). I'm also trying to avoid javascript and would like this to be a 'pure' aspx/code-behind solution (for simplicity's sake among others). All the examples I find are of Modal Popups with the panels pre-defined. Even if it (the popup panel) were something like a list of checkboxes, it could be databound to the SortedList I have ready to go and an OK/Cancel button combination to accept or ignore things. I'm just not sure of what goes where. I'm open to suggestions. Thanks in advance. EDIT: Final solution looks as follows: <asp:TemplateField HeaderText="Company" SortExpression="Company.ShortName"> <ItemTemplate> <asp:Label ID="lblCompany" runat="server" Text='<%# Bind("Company.ShortName") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="lnkCompany" runat="server" Text='<%# Bind("Company.ShortName") %>'></asp:LinkButton> <asp:Panel ID="pnlCompany" runat="server" style="display:none"> <div> <asp:DropDownList ID="ddlCompany" runat="server" ></asp:DropDownList> <br/> <asp:ImageButton ID="btnOKCo" runat="server" ImageUrl="~/Images/greencheck.gif" OnCommand="PopupButton_Command" CommandName="SelectCO" /> <asp:ImageButton ID="btnCxlCo" runat="server" ImageUrl="~/Images/RedX.gif" /> </div> </asp:Panel> <cc1:ModalPopupExtender ID="mpeCompany" runat="server" TargetControlID="lnkCompany" PopupControlID="pnlCompany" BackgroundCssClass="modalBackground" CancelControlID="btnCxlCo" DropShadow="true" PopupDragHandleControlID="pnlCompany" /> </EditItemTemplate> </asp:TemplateField> And in the code-behind, lstIDLabor is the generic List of data lines (of which Company is one of the properties that is also a business object) that is bound to the GridView: Sub PopupButton_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Dim intRow As Integer Dim intVal As Integer RestoreFromSessionVariables() Select Case e.CommandName Case "SelectCO" intRow = grdIDCostLabor.EditIndex Dim ddlCo As DropDownList = CType(grdIDCost.Rows(intRow).FindControl("ddlCompany"), DropDownList) intVal = ddlCo.SelectedValue lstIDLabor(intRow).CompanyID = intVal lstIDLabor(intRow).Company = Company.Read(intVal) Case Else ' End Select MakeSessionVariables() BindGrids() End Sub

    Read the article

  • Using VBA / Macro to highlight changes in excel

    - by Zaj
    I have a spread sheet that I send out to various locations to have information on it updated and then sent back to me. However, I had to put validation and lock the cells to force users to input accurate information. Then I can to use VBA to disable the work around of cut copy and paste functions. And additionally I inserted a VBA function to force users to open the excel file in Macros. Now I'm trying to track the changes so that I know what was updated when I recieve the sheet back. However everytime i do this I get an error when someone savesthe document and randomly it will lock me out of the document completely. I have my code pasted below, can some one help me create code in the VBA forum to highlight changes instead of through excel's share/track changes option? ThisWorkbook (Code): Option Explicit Const WelcomePage = "Macros" Private Sub Workbook_BeforeClose(Cancel As Boolean) Call ToggleCutCopyAndPaste(True) 'Turn off events to prevent unwanted loops Application.EnableEvents = False 'Evaluate if workbook is saved and emulate default propmts With ThisWorkbook If Not .Saved Then Select Case MsgBox("Do you want to save the changes you made to '" & .Name & "'?", _ vbYesNoCancel + vbExclamation) Case Is = vbYes 'Call customized save routine Call CustomSave Case Is = vbNo 'Do not save Case Is = vbCancel 'Set up procedure to cancel close Cancel = True End Select End If 'If Cancel was clicked, turn events back on and cancel close, 'otherwise close the workbook without saving further changes If Not Cancel = True Then .Saved = True Application.EnableEvents = True .Close savechanges:=False Else Application.EnableEvents = True End If End With End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) 'Turn off events to prevent unwanted loops Application.EnableEvents = False 'Call customized save routine and set workbook's saved property to true '(To cancel regular saving) Call CustomSave(SaveAsUI) Cancel = True 'Turn events back on an set saved property to true Application.EnableEvents = True ThisWorkbook.Saved = True End Sub Private Sub Workbook_Open() Call ToggleCutCopyAndPaste(False) 'Unhide all worksheets Application.ScreenUpdating = False Call ShowAllSheets Application.ScreenUpdating = True End Sub Private Sub CustomSave(Optional SaveAs As Boolean) Dim ws As Worksheet, aWs As Worksheet, newFname As String 'Turn off screen flashing Application.ScreenUpdating = False 'Record active worksheet Set aWs = ActiveSheet 'Hide all sheets Call HideAllSheets 'Save workbook directly or prompt for saveas filename If SaveAs = True Then newFname = Application.GetSaveAsFilename( _ fileFilter:="Excel Files (*.xls), *.xls") If Not newFname = "False" Then ThisWorkbook.SaveAs newFname Else ThisWorkbook.Save End If 'Restore file to where user was Call ShowAllSheets aWs.Activate 'Restore screen updates Application.ScreenUpdating = True End Sub Private Sub HideAllSheets() 'Hide all worksheets except the macro welcome page Dim ws As Worksheet Worksheets(WelcomePage).Visible = xlSheetVisible For Each ws In ThisWorkbook.Worksheets If Not ws.Name = WelcomePage Then ws.Visible = xlSheetVeryHidden Next ws Worksheets(WelcomePage).Activate End Sub Private Sub ShowAllSheets() 'Show all worksheets except the macro welcome page Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets If Not ws.Name = WelcomePage Then ws.Visible = xlSheetVisible Next ws Worksheets(WelcomePage).Visible = xlSheetVeryHidden End Sub Private Sub Workbook_Activate() Call ToggleCutCopyAndPaste(False) End Sub Private Sub Workbook_Deactivate() Call ToggleCutCopyAndPaste(True) End Sub This is in my ModuleCode: Option Explicit Sub ToggleCutCopyAndPaste(Allow As Boolean) 'Activate/deactivate cut, copy, paste and pastespecial menu items Call EnableMenuItem(21, Allow) ' cut Call EnableMenuItem(19, Allow) ' copy Call EnableMenuItem(22, Allow) ' paste Call EnableMenuItem(755, Allow) ' pastespecial 'Activate/deactivate drag and drop ability Application.CellDragAndDrop = Allow 'Activate/deactivate cut, copy, paste and pastespecial shortcut keys With Application Select Case Allow Case Is = False .OnKey "^c", "CutCopyPasteDisabled" .OnKey "^v", "CutCopyPasteDisabled" .OnKey "^x", "CutCopyPasteDisabled" .OnKey "+{DEL}", "CutCopyPasteDisabled" .OnKey "^{INSERT}", "CutCopyPasteDisabled" Case Is = True .OnKey "^c" .OnKey "^v" .OnKey "^x" .OnKey "+{DEL}" .OnKey "^{INSERT}" End Select End With End Sub Sub EnableMenuItem(ctlId As Integer, Enabled As Boolean) 'Activate/Deactivate specific menu item Dim cBar As CommandBar Dim cBarCtrl As CommandBarControl For Each cBar In Application.CommandBars If cBar.Name <> "Clipboard" Then Set cBarCtrl = cBar.FindControl(ID:=ctlId, recursive:=True) If Not cBarCtrl Is Nothing Then cBarCtrl.Enabled = Enabled End If Next End Sub Sub CutCopyPasteDisabled() 'Inform user that the functions have been disabled MsgBox " Cutting, copying and pasting have been disabled in this workbook. Please hard key in data. " End Sub

    Read the article

  • Observable Collections

    - by SGWellens
    I didn't think it was possible, but .NET surprised me yet again with a cool feature I never knew existed: The ObservableCollection. This became available in .NET 3.0. In essence, an ObservableCollection is a collection with an event you can connect to. The event fires when the collection changes. As usual, working with the .NET classes is so ridiculously easy, it feels like cheating. The following is small test program to illustrate how the ObservableCollection works. To start, create an ObservableCollection and then store it in the Session object so it will persist between page post backs. I also added the code to pull it out of Session state when there is a page post back:   public partial class _Default : System.Web.UI.Page{    public ObservableCollection<int> MyInts;     // ---- Page_Load ------------------------------     protected void Page_Load(object sender, EventArgs e)    {        if (IsPostBack == false)        {            MyInts = new ObservableCollection<int>();            MyInts.CollectionChanged += CollectionChangedHandler;             Session["MyInts"] = MyInts;  // store for use between postbacks        }        else        {            MyInts = Session["MyInts"] as ObservableCollection<int>;        }    } Here's the event handler I hooked up to the ObservableCollection, it writes status strings to a ListBox. Note: The event handler fires in a different thread than the IIS process thread.     // ---- CollectionChangedHandler -----------------------------------    //    // Something changed in the Observable collection     public void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)    {        // need to dig around to get the current page and control to write to:        // (because this is in a separate thread)        Page CurrentPage = System.Web.HttpContext.Current.Handler as Page;        ListBox LB = CurrentPage.FindControl("ListBoxHistory") as ListBox;         switch (e.Action)        {            case NotifyCollectionChangedAction.Add:                LB.Items.Add("Add: " + e.NewItems[0]);                               break;             case NotifyCollectionChangedAction.Remove:                LB.Items.Add("Remove: " + e.OldItems[0]);                break;             case NotifyCollectionChangedAction.Reset:                LB.Items.Add("Reset: ");                break;             default:                LB.Items.Add(e.Action.ToString());                break;                     }    }  Next, add some buttons and code to exercise the ObservableCollection:     <br />    <asp:Button ID="ButtonAdd" runat="server" Text="Add" OnClick="ButtonAdd_Click" />    <asp:Button ID="ButtonRemove" runat="server" Text="Remove" OnClick="ButtonRemove_Click" />    <asp:Button ID="ButtonReset" runat="server" Text="Reset" OnClick="ButtonReset_Click" />    <asp:Button ID="ButtonList" runat="server" Text="List" OnClick="ButtonList_Click" />    <br />    <asp:TextBox ID="TextBoxInt" runat="server" Width="51px"></asp:TextBox>    <br />    <asp:ListBox ID="ListBoxHistory" runat="server" Height="255px" Width="195px">    </asp:ListBox>    // ---- Add Button --------------------------------------     protected void ButtonAdd_Click(object sender, EventArgs e)    {        int Temp;        if (int.TryParse(TextBoxInt.Text, out Temp) == true)            MyInts.Add(Temp);    }     // ---- Remove Button --------------------------------------     protected void ButtonRemove_Click(object sender, EventArgs e)    {        int Temp;        if (int.TryParse(TextBoxInt.Text, out Temp) == true)            MyInts.Remove(Temp);    }     // ---- Button Reset -----------------------------------     protected void ButtonReset_Click(object sender, EventArgs e)    {        MyInts.Clear();    }     // ---- Button List --------------------------------------     protected void ButtonList_Click(object sender, EventArgs e)    {        ListBoxHistory.Items.Add("MyInts:");        foreach (int i in MyInts)        {            // a bit of tweaking to get the text to be indented            ListItem LI = new ListItem("&nbsp;&nbsp;" + i.ToString());            LI.Text = Server.HtmlDecode(LI.Text);            ListBoxHistory.Items.Add(LI);        }    } Here's what it looks like after entering some numbers and clicking some buttons: An interesting note is that I had to use: System.Web.HttpContext.Current.Response to write to a control on the page. As mentioned earlier, this implies that the notification event is in a thread separate from the IIS thread. Another interesting note: From the online help: Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe What does that mean to Asp.Net developers? If you are going to share an ObservableCollection among different sessions, you'd better make it a static object. I hope someone finds this useful. Steve Wellens

    Read the article

  • Top 50 ASP.Net Interview Questions & Answers

    - by Samir R. Bhogayta
    1. What is ASP.Net? It is a framework developed by Microsoft on which we can develop new generation web sites using web forms(aspx), MVC, HTML, Javascript, CSS etc. Its successor of Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.0, which is used to develop web sites. There are various page extensions provided by Microsoft that are being used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, xml etc. 2. What’s the use of Response.Output.Write()? We can write formatted output  using Response.Output.Write(). 3. In which event of page cycle is the ViewState available?   After the Init() and before the Page_Load(). 4. What is the difference between Server.Transfer and Response.Redirect?   In Server.Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser.  This provides a faster response with a little less overhead on the server.  The clients url history list or current url Server does not update in case of Server.Transfer. Response.Redirect is used to redirect the user’s browser to another page or site.  It performs trip back to the client where the client’s browser is redirected to the new page.  The user’s browser history list is updated to reflect the new address. 5. From which base class all Web Forms are inherited? Page class.  6. What are the different validators in ASP.NET? Required field Validator Range  Validator Compare Validator Custom Validator Regular expression Validator Summary Validator 7. Which validator control you use if you need to make sure the values in two different controls matched? Compare Validator control. 8. What is ViewState? ViewState is used to retain the state of server-side objects between page post backs. 9. Where the viewstate is stored after the page postback? ViewState is stored in a hidden field on the page at client side.  ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. 10. How long the items in ViewState exists? They exist for the life of the current page. 11. What are the different Session state management options available in ASP.NET? In-Process Out-of-Process. In-Process stores the session in memory on the web server. Out-of-Process Session state management stores data in an external server.  The external server may be either a SQL Server or a State Server.  All objects stored in session are required to be serializable for Out-of-Process state management. 12. How you can add an event handler?  Using the Attributes property of server side control. e.g. [csharp] btnSubmit.Attributes.Add(“onMouseOver”,”JavascriptCode();”) [/csharp] 13. What is caching? Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file. 14. What are the different types of caching? ASP.NET has 3 kinds of caching : Output Caching, Fragment Caching, Data Caching. 15. Which type if caching will be used if we want to cache the portion of a page instead of whole page? Fragment Caching: It caches the portion of the page generated by the request. For that, we can create user controls with the below code: [xml] <%@ OutputCache Duration=”120? VaryByParam=”CategoryID;SelectedID”%> [/xml] 16. List the events in page life cycle.   1) Page_PreInit 2) Page_Init 3) Page_InitComplete 4) Page_PreLoad 5) Page_Load 6) Page_LoadComplete 7) Page_PreRender 8)Render 17. Can we have a web application running without web.Config file?   Yes 18. Is it possible to create web application with both webforms and mvc? Yes. We have to include below mvc assembly references in the web forms application to create hybrid application. [csharp] System.Web.Mvc System.Web.Razor System.ComponentModel.DataAnnotations [/csharp] 19. Can we add code files of different languages in App_Code folder?   No. The code files must be in same language to be kept in App_code folder. 20. What is Protected Configuration? It is a feature used to secure connection string information. 21. Write code to send e-mail from an ASP.NET application? [csharp] MailMessage mailMess = new MailMessage (); mailMess.From = “[email protected]”; mailMess.To = “[email protected]”; mailMess.Subject = “Test email”; mailMess.Body = “Hi This is a test mail.”; SmtpMail.SmtpServer = “localhost”; SmtpMail.Send (mailMess); [/csharp] MailMessage and SmtpMail are classes defined System.Web.Mail namespace.  22. How can we prevent browser from caching an ASPX page?   We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache property: [csharp] Response.Cache.SetNoStore (); Response.Write (DateTime.Now.ToLongTimeString ()); [/csharp] 23. What is the good practice to implement validations in aspx page? Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources. 24. What are the event handlers that we can have in Global.asax file? Application Events: Application_Start , Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed,  Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute, Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache Session Events: Session_Start,Session_End 25. Which protocol is used to call a Web service? HTTP Protocol 26. Can we have multiple web config files for an asp.net application? Yes. 27. What is the difference between web config and machine config? Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server. 28.  Explain role based security ?   Role Based Security used to implement security based on roles assigned to user groups in the organization. Then we can allow or deny users based on their role in the organization. Windows defines several built-in groups, including Administrators, Users, and Guests. [xml] <AUTHORIZATION>< authorization > < allow roles=”Domain_Name\Administrators” / >   < !– Allow Administrators in domain. — > < deny users=”*”  / >                            < !– Deny anyone else. — > < /authorization > [/xml] 29. What is Cross Page Posting? When we click submit button on a web page, the page post the data to the same page. The technique in which we post the data to different pages is called Cross Page posting. This can be achieved by setting POSTBACKURL property of  the button that causes the postback. Findcontrol method of PreviousPage can be used to get the posted values on the page to which the page has been posted. 30. How can we apply Themes to an asp.net application? We can specify the theme in web.config file. Below is the code example to apply theme: [xml] <configuration> <system.web> <pages theme=”Windows7? /> </system.web> </configuration> [/xml] 31: What is RedirectPermanent in ASP.Net?   RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses. 32: What is MVC? MVC is a framework used to create web applications. The web application base builds on  Model-View-Controller pattern which separates the application logic from UI, and the input and events from the user will be controlled by the Controller. 33. Explain the working of passport authentication. First of all it checks passport authentication cookie. If the cookie is not available then the application redirects the user to Passport Sign on page. Passport service authenticates the user details on sign on page and if valid then stores the authenticated cookie on client machine and then redirect the user to requested page 34. What are the advantages of Passport authentication? All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site. Users can maintain his/ her information in a single location. 35. What are the asp.net Security Controls? <asp:Login>: Provides a standard login capability that allows the users to enter their credentials <asp:LoginName>: Allows you to display the name of the logged-in user <asp:LoginStatus>: Displays whether the user is authenticated or not <asp:LoginView>: Provides various login views depending on the selected template <asp:PasswordRecovery>:  email the users their lost password 36: How do you register JavaScript for webcontrols ? We can register javascript for controls using <CONTROL -name>Attribtues.Add(scriptname,scripttext) method. 37. In which event are the controls fully loaded? Page load event. 38: what is boxing and unboxing? Boxing is assigning a value type to reference type variable. Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable. 39. Differentiate strong typing and weak typing In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime. 40. How we can force all the validation controls to run? The Page.Validate() method is used to force all the validation controls to run and to perform validation. 41. List all templates of the Repeater control. ItemTemplate AlternatingltemTemplate SeparatorTemplate HeaderTemplate FooterTemplate 42. List the major built-in objects in ASP.NET?  Application Request Response Server Session Context Trace 43. What is the appSettings Section in the web.config file? The appSettings block in web config file sets the user-defined values for the whole application. For example, in the following code snippet, the specified ConnectionString section is used throughout the project for database connection: [csharp] <em><configuration> <appSettings> <add key=”ConnectionString” value=”server=local; pwd=password; database=default” /> </appSettings></em> [/csharp] 44.      Which data type does the RangeValidator control support? The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date. 45. What is the difference between an HtmlInputCheckBox control and anHtmlInputRadioButton control? In HtmlInputCheckBoxcontrol, multiple item selection is possible whereas in HtmlInputRadioButton controls, we can select only single item from the group of items. 46. Which namespaces are necessary to create a localized application? System.Globalization System.Resources 47. What are the different types of cookies in ASP.NET? Session Cookie – Resides on the client machine for a single session until the user does not log out. Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never. 48. What is the file extension of web service? Web services have file extension .asmx.. 49. What are the components of ADO.NET? The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection. 50. What is the difference between ExecuteScalar and ExecuteNonQuery? ExecuteScalar returns output value where as ExecuteNonQuery does not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.

    Read the article

  • The name 'GridView1' does not exist in the current context

    - by sameer
    hi all, I have two files named as TimeSheet.aspx.cs and TimSheet.aspx ,code of the file are given below for your reference. when i build the application im getting error "The name 'GridView1' does not exist in the current context" even thought i have a control with the id GridView1 and i have added the runat="server" as well. Im not able to figure out what is causing this issue.Can any one figure whats happen here. Thanks & Regards, ======================================= TimeSheet.aspx.cs ======================================= #region Using directives using System; using System.Data; 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; using TSMS.Web.UI; #endregion public partial class TimeSheets: Page { protected void Page_Load(object sender, EventArgs e) { FormUtil.RedirectAfterUpdate(GridView1, "TimeSheets.aspx?page={0}"); FormUtil.SetPageIndex(GridView1, "page"); FormUtil.SetDefaultButton((Button)GridViewSearchPanel1.FindControl("cmdSearch")); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { string urlParams = string.Format("TimeSheetId={0}", GridView1.SelectedDataKey.Values[0]); Response.Redirect("TimeSheetsEdit.aspx?" + urlParams, true); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { } } ======================================================= TimeSheet.aspx ======================================================= <%@ Page Language="C#" Theme="Default" MasterPageFile="~/MasterPages/admin.master" AutoEventWireup="true" CodeFile="TimeSheets.aspx.cs" Inherits="TimeSheets" Title="TimeSheets List" %> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">Time Sheets List</asp:Content> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <data:GridViewSearchPanel ID="GridViewSearchPanel1" runat="server" GridViewControlID="GridView1" PersistenceMethod="Session" /> <br /> <data:EntityGridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" DataSourceID="TimeSheetsDataSource" DataKeyNames="TimeSheetId" AllowMultiColumnSorting="false" DefaultSortColumnName="" DefaultSortDirection="Ascending" ExcelExportFileName="Export_TimeSheets.xls" onrowcommand="GridView1_RowCommand" > <Columns> <asp:CommandField ShowSelectButton="True" ShowEditButton="True" /> <asp:BoundField DataField="TimeSheetId" HeaderText="Time Sheet Id" SortExpression="[TimeSheetID]" ReadOnly="True" /> <asp:BoundField DataField="TimeSheetTitle" HeaderText="Time Sheet Title" SortExpression="[TimeSheetTitle]" /> <asp:BoundField DataField="StartDate" DataFormatString="{0:d}" HtmlEncode="False" HeaderText="Start Date" SortExpression="[StartDate]" /> <asp:BoundField DataField="EndDate" DataFormatString="{0:d}" HtmlEncode="False" HeaderText="End Date" SortExpression="[EndDate]" /> <asp:BoundField DataField="DateOfCreation" DataFormatString="{0:d}" HtmlEncode="False" HeaderText="Date Of Creation" SortExpression="[DateOfCreation]" /> <data:BoundRadioButtonField DataField="Locked" HeaderText="Locked" SortExpression="[Locked]" /> <asp:BoundField DataField="ReviewedBy" HeaderText="Reviewed By" SortExpression="[ReviewedBy]" /> <data:HyperLinkField HeaderText="Employee Id" DataNavigateUrlFormatString="EmployeesEdit.aspx?EmployeeId={0}" DataNavigateUrlFields="EmployeeId" DataContainer="EmployeeIdSource" DataTextField="LastName" /> </Columns> <EmptyDataTemplate> <b>No TimeSheets Found!</b> </EmptyDataTemplate> </data:EntityGridView> <asp:GridView ID="GridView2" runat="server"> </asp:GridView> <br /> <asp:Button runat="server" ID="btnTimeSheets" OnClientClick="javascript:location.href='TimeSheetsEdit.aspx'; return false;" Text="Add New"></asp:Button> <data:TimeSheetsDataSource ID="TimeSheetsDataSource" runat="server" SelectMethod="GetPaged" EnablePaging="True" EnableSorting="True" EnableDeepLoad="True" > <DeepLoadProperties Method="IncludeChildren" Recursive="False"> <Types> <data:TimeSheetsProperty Name="Employees"/> <%--<data:TimeSheetsProperty Name="TimeSheetDetailsCollection" />--%> </Types> </DeepLoadProperties> <Parameters> <data:CustomParameter Name="WhereClause" Value="" ConvertEmptyStringToNull="false" /> <data:CustomParameter Name="OrderByClause" Value="" ConvertEmptyStringToNull="false" /> <asp:ControlParameter Name="PageIndex" ControlID="GridView1" PropertyName="PageIndex" Type="Int32" /> <asp:ControlParameter Name="PageSize" ControlID="GridView1" PropertyName="PageSize" Type="Int32" /> <data:CustomParameter Name="RecordCount" Value="0" Type="Int32" /> </Parameters> </data:TimeSheetsDataSource> </asp:Content>

    Read the article

  • Find Label Control in Repeater Asp.net

    - by user2769165
    I am using repeater and I want to find the label control in my repeater. here is my code <asp:Repeater ID="friendRepeater" runat="server"> <table cellpadding="0" cellspacing="0"> <ItemTemplate> <tr style=" width:700px; height:120px;"> <td> <div style=" padding-left:180px;"> <div id="leftHandPost" style="float:left; width:120px; height:120px; border: medium solid #cdaf95; padding-top:5px;"> <div id="childLeft" style=" padding-left:5px;"> <div id="photo" style=" border: thin solid black; width:100px;height:100px;"> <asp:Image id="photoImage" runat="server" ImageUrl='<%# String.Concat("Images/", Eval("Picture")) %>' Width="100px" Height="100px" /> </div> </div><!--childLeft--> </div><!--leftHandPost--> </div> </td> <td> <div id="rightHandPost" style=" float:right; padding-right:260px;"> <div id="childRight" style="width:400px; height:120px; border: medium solid #cdaf95; padding-top:5px; padding-left:10px;"> <strong><asp:Label id="lblName" runat="server"><%# Eval("PersonName") %></asp:Label></strong><br /> <div style=" float:right; padding-right:10px;"><asp:Button runat="server" Text="Add" onClick="add" /></div><br /> <asp:Label id="lblID" runat="server"><%# Eval("PersonID") %></asp:Label><br /> <asp:Label id="lblEmail" runat="server"><%# Eval("Email") %></asp:Label> </div><!--childRight--> </div><!--rightHandPost--> </td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr style=" width:700px; height:120px;"> <td> <div style=" padding-left:180px;"> <div id="Div1" style="float:left; width:120px; height:120px; border: medium solid #cdaf95; padding-top:5px;"> <div id="Div2" style="padding-left:5px;"> <div id="Div3" style=" border: thin solid black; width:100px;height:100px;"> <asp:Image id="photoImage" runat="server" ImageUrl='<%# String.Concat("Images/", Eval("Picture")) %>' Width="100px" Height="100px" /> </div> </div><!--childLeft--> </div><!--leftHandPost--> </div> </td> <td> <div id="Div4" style=" float:right; padding-right:260px;"> <div id="Div5" style="width:400px; height:120px; border: medium solid #cdaf95; padding-top:5px; padding-left:10px;"> <strong><asp:Label id="lblName" runat="server"><%# Eval("PersonName")%></asp:Label></strong> <div style=" float:right; padding-right:10px;"><asp:Button id="btnAdd" runat="server" Text="Add" onClick="add"></asp:Button></div><br /> <br /> <asp:Label id="lblID" runat="server"><%# Eval("PersonID") %></asp:Label><br /> <asp:Label id="lblEmail" runat="server"><%# Eval("Email") %></asp:Label> </div><!--childRight--> </div><!--rightHandPost--> </td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> Here is the code behind for the add button. protected void add(object sender, EventArgs e) { DateTime date = DateTime.Now; System.Web.UI.WebControls.Label la = (System.Web.UI.WebControls.Label)friendRepeater.FindControl("PersonID"); String id = la.Text; try { MySqlConnection connStr = new MySqlConnection(); connStr.ConnectionString = "Server = localhost; Database = healthlivin; Uid = root; Pwd = khei92;"; String insertFriend = "INSERT INTO contactFriend(friendID, PersonID, PersonIDB, date) values (@id, @personIDA, @personIDB, @date)"; MySqlCommand cmdInsertStaff = new MySqlCommand(insertFriend, connStr); cmdInsertStaff.Parameters.AddWithValue("@id", "F000004"); cmdInsertStaff.Parameters.AddWithValue("@personIDA", "M000001"); cmdInsertStaff.Parameters.AddWithValue("@personIDB", id); cmdInsertStaff.Parameters.AddWithValue("@date", date); connStr.Open(); cmdInsertStaff.ExecuteNonQuery(); MessageBox.Show("inserted"); connStr.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } I have get the error of Object reference not set to an instance of an object. I think is because there are no value in the Label. The Find Control are not working. May I know how can fix this problem? Thank you very much

    Read the article

< Previous Page | 6 7 8 9 10