Posts

Donate

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

Read Or Parse XML Using XPathDocument In C#

Good day! In this example, I will show you how to read an XML file using XPathNavigator and XPathDocument classes in .NET. When using these classes, make sure to include the System.Xml and System.Xml.XPath namespaces in your file. XML File <?xml version="1.0" encoding="utf-8" ?> <Invoice xmlns:inv= "http://salesorgchart.abcdefg.com" > <inv:Customers> <inv:TotalSales>134.49</inv:TotalSales> -<inv:Customer> <inv:Date>2013-11-15</inv:Date> <inv:Number>10001</inv:Number> <inv:CustomerName>Cherry Pie</inv:CustomerName> <inv:PONumber>30002</inv:PONumber> <inv:Address>Cebu City Philippines</inv:Address> -<inv:Products> -<inv:Product> <inv:Code>AE445</inv:Code> <inv:Category>Liquid Milk</inv:Category> <inv:Name>Devondale</inv:Name>

Show SQL Query Result As XML Using Sql Server FOR XML()

Image
Hello, Given that you are required to show the results of a query into an XML format, T-SQL has a function called For XML to achieve that output as shown below. Screenshot I have created two scripts to achieve the desired result as above. The first script will alias a column name with @AttributeName that signifies an attribute which will then be added to Assigned node using FOR XML Path() function. Use NorthwindCrudApp Go SELECT TOP 3 ProductID as "@ProductID" , ProductName as "@ProductName" , UnitsInStock as "@UnitsInStock" , UPPER (ProductName) as [text()] FROM Products As Products ORDER BY ProductID FOR XML PATH( 'Assigned' ), Root( 'DATA' ); The second script also creates column alias for each column using the syntax NodeName/@Attribute similar to an XPath expression. SELECT TOP 3 ProductID as "Assigned/@ProductID" , ProductName as "Assigned/@ProductName" , UnitsIn

Set DataGridTemplateColumn Control to ReadOnly in WPF

Image
Hi all, There was a question raised on how to set a control (ex. TextBox) inside the DataGridTemplateColumn of a WPF DataGrid to ReadOnly. The solution to that is to get the DataGridRow followed by accessing the DataGridCell and then get the VisualChild control inside the DataGridCell. By then, you can set the control's property IsReadOnly to true . XAML Code <DataGrid x:Name= "dgPerson" Grid.Column= "2" Grid.Row= "2" CanUserDeleteRows= "False" AutoGenerateColumns= "False" CanUserAddRows= "False" > <DataGrid.Columns> <DataGridTemplateColumn Header= "ID" Width= "150" > <DataGridTemplateColumn.CellTemplate> <DataTemplate > <TextBox Name= "txtID" Text= "{Binding ID, Mode=OneWay}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn H

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... } }

How To Send Email Using SmtpClient In C# Example

Here's a simple class that sends email using SmtpClient class. The code references System.Net.Mail namespace to access the SmtpClient class and other related assemblies. using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Net.Mail; public class SendEMail { public void SendMailToClient( string from , string to, string subject, string body) { try { MailMessage message = new MailMessage(); SmtpClient client = new SmtpClient(); message.From = new MailAddress( from ); message.To.Add(to); message.Subject = subject; message.Body = body; message.IsBodyHtml = true ; //client.Host = ConfigurationManager.AppSettings["Host"]; client.UseDefaultCredentials = false ; client.Send(message); } catch (Exception ex) { throw

LINQ to Entities does not recognize the method 'System.String ToString()

When working with Dropdownlists in ASP.NET MVC, I encountered an error as stated in the title of this post when casting an int variable through LINQ Select() statement. List<SelectListItem> itemCountries = new List<SelectListItem>(); itemCountries.AddRange(( from country in _context.CascadeCountries select country) .Select(x => new SelectListItem { Value = x.CountryID.ToString(), //error here... Text = x.CountryName }).ToList()); After doing some research, I found out that the statement returned by the Select statement above is IQueryable and the itemCountries variable is an IEnumerable . So, the fix for this issue is to cast the LINQ statement with AsEnumerable() and then followed by the Select() statement which sets the values for the SelectListItems properties. List<SelectListItem> itemCountries = new List<SelectListItem>(); itemCountries.AddRange(( from country in _context.Casca

Using Lag() In SQL Server To Retrieve Previous Row Value

I have this old T-SQL script that retrieves previous row value of a certain order year which uses a combination of derived tables, left join and group by to achieve the desired result. Upon visiting this script and doing some research on new T-SQL functions, I encountered an article from SQL Authority on How To Access Previous Row and Next Row in Select statement . So, given the time I quickly converted my script using Lag() function and was surprised to see that my new script looks clean and orderly compared to the old one. Old T-SQL Script SELECT Curr_Data.Year_Order, Curr_Data.Customer_Count AS Customer_Count, Prev_Data.Customer_Count AS Previous_Customer_Count, Curr_Data.Customer_Count - Prev_Data.Customer_Count AS Growth FROM ( SELECT YEAR (Orderdate) AS Year_Order, COUNT ( DISTINCT CustomerID) AS Customer_Count FROM CustomerOrders GROUP BY YEAR (Orderdate)) AS Curr_Data LEFT OUTER JOIN ( SELECT YEAR (Orderdate) A

Escape Curly Brace In C# String.Format()

Image
To escape curly braces in String.Format(), you have to prepend "{" symbol in the opening brace and append "}" in the closing brace as shown below. Code: string firstName = "Michael" ; string lastName = "Jordan" ; string output = String.Format( "Your name is: {{ {0}, {1} }}" , firstName, lastName); Console.WriteLine(output); Output:

Donate