Posts

Donate

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:

Attach Single Event To A Control Array At Run Time Using LINQ And C#

In a scenario wherein you need to attach a single event like CheckedChanged() to a control array such as CheckBox controls, the common way to do it is using for each or for loop. Another way to achieve it is using LINQ's ForEach() method as demonstrated below. Event Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 void CheckBoxGeneric_CheckedChanged ( object sender, EventArgs e) { var checkBox = (CheckBox)sender; if (checkBox.Name == "chkBurger" ) { //... } else if (checkBox.Name == "chkSoda" ) { //... } else { //... } } Attach the event to the control array 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 private CheckBox[] OrderItems; OrderItems = new CheckBox[] { chkBurger, chkSoda, chkIceCream }; private void Form1_Load ( object sender, EventArgs e) { //solution 1 using foreach loop //foreach (var checkControl in OrderItems) //{ // checkControl.CheckedChanged += new EventHandler(CheckBoxGeneric_CheckedChanged);

Using Microsoft.mshtml With The WebBrowser Control In C#

Image
Hello and Good Evening When working with a WebBrowser to extract information from a webpage, the most common classes that are probably used to traverse or navigate it's DOM are from the System.Windows.Forms namespace such as HtmlDocument, HtmlElementCollection and etc. Another way to navigate and traverse the DOM of the WebBrowser's HTMLDocument is using the Microsoft.mshtml namespace which contains interfaces for the rendering engine of Internet Explorer. So to access those interfaces and in your application, add reference to Microsoft.mshtml. In the code sample below, set alias for the Microsoft.mshtml namespace. You need to explicitly specify the namespace of a class or interface as MSHTML since Windows.Forms also have same class names with the former. And one thing to remember is that, empty results in mshtml does not yield nulls. Instead, it produces DBNull value. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 using MSHTML = mshtml; //set namespace alia

IsDBNull() Equivalent in C#

When working with DBNull values in VB.NET you can check if that object is of type DBNull using IsDBNull(object) . So, to do this in C#, I have two options to do this. The first one is to get the type of that object and compare it with typeof(System.DBNull). Code 1 2 3 4 5 var attribute = element.getAttribute( "data-mixvids" ); if (attribute.GetType() != typeof (System.DBNull)) { lstElementVids.Add(element.getAttribute( "data-mixvids" )); } The other one is presented in MSDN docs using DBNull.Value.Equals(object) which returns true. Code 1 2 3 4 5 var attribute = element.getAttribute( "data-mixvids" ); if (!System.DBNull.Value.Equals(attribute)) { lstElementVids.Add(element.getAttribute( "data-mixvids" )); } Reference: MSDN Convert.IsDBNull Method (Object)

WebBrowser How To Fire Click Event Of Input Submit Element In C# And VB.NET

Given in a webpage there are several input elements and you want to fire the click event of an input element of type submit, here's how to do it using the Webbrowser control. C# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 HtmlElementCollection htmlElementCollection = new HtmlElementCollection(); if (WebBrowser1.Document != null ) { htmlElementCollection = WebBrowser1.Document.GetElementsByTagName( "input" ); if (htmlElementCollection != null && htmlElementCollection.Count > 0) { foreach (HtmlElement element in htmlElementCollection) { if (element.GetAttribute( "value" ).Equals( "Submit" )) { element.InvokeMember( "click" ); } } } } VB.NET 1 2 3 4 5 6 7 8 9 10 11 12 13 Dim htmlElementCollection As HtmlElementCollection If (WebBrowser1.Document IsNot Nothing ) Then With WebBrowser1.Document htmlElem

Regular Expression Extract Url From String Using Regex.Matches() In C#

Here's how to extract url(s) from a string or document using Regex.Matches() method. The Regex.Matches() method returns an array object MatchCollection in which you can access individual elements using it's index. Code: 1 2 3 4 5 6 7 8 9 10 11 12 string pattern = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?" ; string Input = "<<abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ\"abcd\" href=\"https://mediatemple.net\"" + "Sample text for testing>http://regexr.com/foo.html?q=bar>" ; string url1 = string .Empty; string url2 = string .Empty; if (Regex.Matches(Input, pattern).Count > 0) { MatchCollection matches = Regex.Matches(Input, pattern); url1 = matches[0].Value; url2 = matches[1].Value; }

Donate