Posts

Showing posts with the label ASP.NET Web Forms

Donate

Using Dapper ORM In ASP.NET Web Forms

Image
Hello, This is a simple tutorial of using Dapper Micro ORM in an ASP.NET Webform application. According to Wikipedia, Dapper is an object-relational mapping (ORM) product for the Microsoft .NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks. The key feature of Dapper is performance as presented in Dapper website (github). It is second to Hand coded SQLDataReader class when querying specific number of records. To get started with, create an Empty ASP.NET WebForm project and then add the Dapper to our project via NuGet. Make sure to alter the connection string in Web.Config to point to your database. Then we need to add one interface and three classes in our Models folder which applies the idea of Repository. Customer.cs public class Customer { public int CustomerID { get ; set ; } publ

ASP.NET Web Forms Multiple Server Validation Controls Wide Space Issue

Image
Good day! When working with multiple server validation controls for one input control, you often encountered wide space gap if the validation controls are placed inside a single container such as div or td such as the sample screenshot below. The solution to remove the wide gap is to set the Display property of the validation controls to Dynamic. <td> <asp:TextBox ID= "txtCreditLimit" runat= "server" Width= "150" /> <asp:RegularExpressionValidator ValidationGroup= "valCustomerEntry" Display= "Dynamic" ID= "regexpName" runat= "server" ErrorMessage= "The value entered is not valid" ControlToValidate= "txtCreditLimit" ValidationExpression= "\d+(\.\d*)?|\.\d+" ForeColor= "Red" /> <asp:RequiredFieldValidator ValidationGroup= "valCustomerEntry" Display= "Dynamic" ID= "RequiredFieldValidator6" runat= "ser

Using AJAX Control Toolkit AutoCompleteExtender In ASP.NET 4.5 Web Forms

Image
Hello all, I have posted in VBForums codebank on how to integrate Ajax Toolkit's AutoCompleteExtender control in your ASP.NET 4.5 Web Forms project. The thread is in VB.NET but if your using C# just replace the code behind as described in Step 4 with the snippet below. Code Behind private static AdventureWorks2012Entities _context; [ScriptMethod()] [WebMethod] public static List< string > GetCountries( string prefixText, int count) { _context = new AdventureWorks2012Entities(); var result = ( from country in _context.CountryRegions.AsEnumerable() where country.Name.ToLower().StartsWith(prefixText, StringComparison.OrdinalIgnoreCase) select country.Name).Take(count); return result.ToList(); } [ScriptMethod()] [WebMethod] public static object GetCountryInfo( string Country) { _context = new AdventureWorks2012Entities(); var result = ( from country in _context.CountryRegions.AsEnumerable() where country.Name.ToLower().Equals(C

Invalid postback or callback argument in ASP.NET (_doPostBack in jQuery UI Confirmation Dialog)

Hello, I'm currently working with ASP.NET GridView control that shows a confirmation dialog using jQuery UI instead of the classic JavaScript confirm dialog that prompts a user to delete a certain record. However, integrating that with the GridView control was slightly tricky in the sense that I was stuck with Invalid postback or callback argument error. Since this is ASP.NET Webforms, you have to deal with Postback hell issues. :) jQuery UI Dialog that trigger's postback buttons: { "Yes" : function () { __doPostBack(btnUniqueID, '' ); $( this ).dialog( "close" ); }, "No" : function () { $( this ).dialog( "close" ); return false ; } } After doing some research, I came up with two solutions. The first one is to set EnableEventValidation of Page directive to false for page level effect. Or you can set it in web.config for project scope. Page Directive Solution <%@ Page Language= "C#" AutoEventWire

Retrieve Current Row Index Of ASP.NET Web Forms GridView Control On RowCommand

Hi, To retrieve the current row index of a GridView control on RowCommand event, you have to access the NamingContainer property of a control which belongs to that GridViewRow. In the example below, I have a LinkButton control declared inside a TemplateField. ASPX Code <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID= "lbtnDelete" CSSClass= "btn" CommandName= "Delete" Text= "Delete" runat= "server" /> </ItemTemplate> </asp:TemplateField> Code Behind protected void gvCustomers_RowCommand( object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Delete" ) { GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer); int RowIndex = gvr.RowIndex; //TODO: other codes here... } }

Bootstrap DatePicker Control In ASP.NET Web Forms

Image
Here's how to integrate Bootstrap DatePicker widget in you ASP.NET Webforms Project. First, you need to add reference to the following JS and CSS files: bootstrap.min.css , bootstrap-datepicker3.standalone.css , jquery-1.11.1.min.js , bootstrap.min.js , bootstrap-datepicker.min.js . 1 2 3 4 5 <link rel= "stylesheet" href= "Content/bootstrap.min.css" /> <link rel= "stylesheet" href= "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/css/bootstrap-datepicker3.standalone.css" /> <script type= "text/javascript" src= "Scripts/jquery-1.11.1.min.js" ></script> <script type= "text/javascript" src= "Scripts/bootstrap.min.js" ></script> <script type= "text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.1/js/bootstrap-datepicker.min.js" ></script> Create a simple registration form with B

Removing Hyperlink Or LinkButton In A GridViewColumn Based From A Condition Or Value

Image
There was a question raised from the forum on how to remove a hyperlink control in a GridViewColumn if a given condition is met. In the example below, the hyperlink(LinkButton) is disabled if Units In Stock is zero (0). A solution is to disable the LinkButton in the RowDataBoundEvent . 1 2 3 4 5 6 7 8 9 10 11 protected void gvUnitSummary_RowDataBound( object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (Convert.ToInt32(e.Row.Cells[3].Text) == 0) { LinkButton lnkUnitID = (LinkButton)e.Row.FindControl( "lnkProducts" ); lnkUnitID.Enabled = false ; } } } Another solution is to change the column from BoundField to TemplateField. The TemplateField contains a LinkButton and a Label control. Set the Visibility property of the controls accordingly such as LinkButton will be shown if Units In Stock is greater than 0. Otherwise, show the Label control instead. 1 2

Append QueryString To PostBackUrl Attribute In ASP.NET Web Forms LinkButton Control Inside GridView Control

There was a question raised in the forum on how to append query string to a PostbackUrl attribute in an ASP.NET LinkButton inside the template field of a GridView control. To answer that, one possible solution is to set the PostBackUrl with String.Format() method where you can include the desired query string of that url. 1 2 3 4 <asp:LinkButton ID= "lnkProductPage" runat= "server" PostBackUrl= '<%# String.Format("ProductPage.aspx?Id={0}", Eval("ID"))%>' CausesValidation= "false" Text= '<%# Eval("ID")%>' > </asp:LinkButton>

ASP.NET FormView CRUD With Entity Framework (VB.NET)

Image
The VB.NET version of this post ASP.NET FormView CRUD with Entity Framework is provided in the ASP.NET Codebank section of VBForums ASP.NET FormView CRUD (Create, Update, Delete) with Entity Framework . Screenshots

ASP.NET FormView CRUD With Entity Framework

Image
Most of the examples on FormView Web Server control use DataSource wizard controls such as SqlDatasource or ObjectDataSource when assigning value to the FormView's DataSource property. However, using those controls have drawbacks such as maintainability. I also found samples out there using ADO.NET. Enough with the chit-chat and let's proceed with coding. I'll post the create table statement, code behind and the aspx markup. SQL Code: USE [Books] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[BookDetails]( [BookSerialNo] [int] IDENTITY (1,1) NOT NULL , [BookISBN] [ nchar ](15) NULL , [BookTitle] [varchar](120) NULL , [BookAuthor] [varchar](60) NULL , [BookPublisher] [varchar](50) NULL , [BookCategory] [varchar](20) NULL , PRIMARY KEY CLUSTERED ( [BookSerialNo] ASC ) WITH (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_

DataKey Value Is Null In ItemDeleting Event Of ASP.NET Web Forms FormView Control

Image
Hello, Normally, you can access the DataKey object value of a FormView control to it's wired events. Since I'm using Entity Framework as Datasource of a FormView control instead of DataSource control wizards, the DataKey object value of the FormView control returns null instead of an ID in the ItemDeleting event of that object. After putting several breakpoints to it's events, I came up with a fix that is to query the DB again and then bind it's result to the DataSource property of the FormView Control. That is call BindFormView() method when CommandName is equal to "Delete" in the ItemCommand event of the control. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 protected void FormViewBookDetails_ItemCommand( object sender, FormViewCommandEventArgs e) { if (e.CommandName == "Cancel" ) { FormViewBookDetails.ChangeMode(FormViewMode.ReadOnly); } else if (e.CommandName == "Edi

Enable ASP.NET Control After Validation Of Prior Control Succeeded Using JavaScript In ASP.NET

Given you have a simple form below with two TextBox controls. The second TextBox is disabled during pageload. Ifyou want to enable the second TextBox control if the validation of the first/prior control succeeded, the solution for this is using client side approach which is to check the visibility property through JavaScript/jQuery. HTML Code 1 2 3 4 5 6 7 8 9 10 11 <div id= "ContactForm" > <asp:Label id= "lblEmail" Text= "Email Address:" AssociatedControlID= "txtEmail" Runat= "server" /> <asp:TextBox id= "txtEmail" Runat= "server" /> <asp:RegularExpressionValidator id= "regEmail" ControlToValidate= "txtEmail" Text= "(Invalid email)" ValidationExpression= "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Runat= "server" /> <asp:Label id= &qu

ASP.NET Trigger Onchange Event Of DropDownList Inside GridView Using jQuery

Image
There was a question in a forum if how can we trigger an onchange event of a DropDownList control inside a GridView template field. This time using unobtrusive approach. So in order to understand a bit further, the GridView control when rendered to the browser becomes a table element while DropDownList becomes a Select control. So, to trigger the event we need to traverse the GridView control then find the Select control and attach a change event. Here's a solution using jQuery. HTML Markup: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <asp:GridView ID= "gvItem" runat= "server" AutoGenerateColumns= "False" > <Columns> <asp:BoundField DataField= "ID" HeaderText= "ID" /> <asp:BoundField DataField= "ProductName" HeaderText= "ProductName" /> <asp:TemplateField HeaderText= "Time Slot" > <

ASP.NET WebForms Change GridView Sort Link Color

Image
Here's how to change the color of GridView SortLink using CSS. ASPX Markup 1 2 3 4 5 6 7 8 9 10 11 12 <asp:GridView ID= "GridVwPagingSorting" runat= "server" AutoGenerateColumns= "False" Font-Names= "Verdana" AllowPaging= "True" AllowSorting= "True" PageSize= "5" Width= "75%" OnPageIndexChanging= "PageIndexChanging" BorderColor= "#CCCCCC" BorderStyle= "Solid" BorderWidth= "1px" OnSorting= "Sorting" > <AlternatingRowStyle BackColor= "#BFE4FF" /> <PagerStyle BorderColor= "#CCCCCC" BorderStyle= "Solid" BorderWidth= "1px" /> <HeaderStyle CssClass= "gridViewHeader" /> <RowStyle Height= "20px" Font-Size= "13px" BorderColor= "#CCCCCC" BorderStyle= "Solid" BorderWidth= "1px" /> <

Donate