How do you format a date variable in a GridView?
<asp:BoundField DataField="CreatedOn" DataFormatString="{0:M/dd/yyyy}" HtmlEncode="false" />######Other Resources:
<asp:BoundField DataField="CreatedOn" DataFormatString="{0:M/dd/yyyy}" HtmlEncode="false" />######Other Resources:
A useful addition to ASP .NET 2.0 is the ability to register web controls in web.config. In ASP .NET 1.1, if you wanted to use a custom server control on twenty different pages, you had to register it on all twenty of those pages:
<%@ Register tagprefix="tagprefix" Namespace="Namespace" Assembly="Assembly" %>In ASP .NET 2.0, you can register the server control in the controls section of web.config once and use it in whatever page you want of the web application.
<pages><controls><add tagPrefix="MyTagPrefix"namespace="My.Namespace"assembly="MyAssembly"/></controls> <!-- Other elements go here --> </pages>
Access modifiers, as their name suggests, control who sees what in an application. C# has 4 basic access modifiers (thereâs also a 5th one, but more on that later). Here they are, listed from least restrictive to most restrictve.
public: accessible anywhere.protected: accessible to current class and all derived classes.internal: accessible to any class in the current assembly.private: accessible to current class only.Easy enough to understand.
public namespace AwesomeNewNamespace { ⦠} will produce a compile-time error. private class AwesomeNewClass { ⦠} will produce a compile-time error. This makes sense if you think about it â how exactly would you use a private or a protected class?? class NotSoCool { ⦠} is equivalent to internal class NotSoCool { ⦠}.void SomeAwesomeMethod() { ⦠} is equivalent to private void SomeAwesomeMethod() { ⦠}.public voidMethod() { protected string someString; will produce a compile-time error.internal class Base { ⦠} public class Child : Base { } will produce a compile-time error. Now that we got that out of the way, letâs take a look at that 5th modifier that I mentioned at the beginning. This would be the compound modifier protected internal. After looking at it for a minute, you would think that it does what other compound modifiers in .NET do. For example, protected virtual void AwesomeMethod() makes AwesomeMethod both virtual and protected, so youâd think that protected internal AwesomeClass { ⦠} would make the class both protected and internal (i.e., it is only accessible to derived classes in the assembly) but you would be wrong. For some bizarre reason that I have yet to fathom, the powers-to-be have decided that protected internal means protected or internal (so that the method is available to all derived classes as well as all classes in the current assembly).
Something Iâve had to do often. Until now, Iâve gone through the âlaborousâ (hehe) process of remembering what stored procedures Iâve added and granting EXECUTE permissions to whatever user for each procedure. I was sure that there was an easier way to grant the permission on all stored procedures, and there is!
GRANT EXECUTE TO [Insert the name of the user here]
If youâre using SQL Server 2000, you donât have it so easy. However, hereâs an article on how to create a stored procedure to do the same.
A quickie. The Obsolete attribute marks a class or method as (pardon the redundancy) obsolete. Usage:
[System.Obsolete("This is an obsolete class; use NonObsoleteClassInstead")]public class ObsoleteClassExample{// Internals of the class } public class NormalClass{// ⦠[System.Obsolete("This method is absolute; use NonObsoleteMethodInSomeClass")]public void ObsoleteMethodExample(string blah){// Internals of the method } // â¦}No, there isnât any difference in marking a class vs. method as obsolete. I just wanted to create two code blocks, go figure. :p
When you use a class/method marked as obsolete, VS 2005 shows you a nice warning in the âError Listâ pane.
Suppose you have a static readonly string whose value you donât know until runtime. Maybe you have to read it from FileAbcdefgh.txt when certain condition is true and read it from FileXyz.txt when itâs not. But once set, the value should never be modified again.
Iâm assuming you guessed that the solution to the problem is static constructors. You guessed right.
Static constructors, like the null coalescing operator, are a C# feature I was not aware of until fairly recently.
Static constructors look fairly similar to normal (default) constructors:
public class StaticConstructorTestClass{private static readonly string someStaticString = string.Empty; static StaticConstructor(){someStaticString = GetFromDatabaseOrWhatever();} private static string GetFromDatabaseOrWhatever(){// Do the processing here return "This is a string I got from database";}}When creating static constructors, keep these rules in mind:
Only one static constructor per class.The constructor canât have any parameters.The constructor canât have an access modifier (public/private/etc).The constructor executes before any instance constructor.The constructor executes only one time per class.Database access has to be my least favorite activity to code, right up there with coding public data access (to private fields). The worst thing about coding database access is â easily â the need to check for null values. I recently found a nugget in .NET that makes the process a bit less painless, and Iâm putting it out here in the hopes that it will help somebody avoid this:
public void Read(){// ⦠System.Data.SqlClient.SqlDataReader rdr = new System.Data.SqlClient.SqlDataReader(); if (!rdr.IsDBNull(0)){// Yay! Itâs not null.} if (!rdr.IsDBNull(1)){// Wow, the second field is not null either. } if (!rdr.IsDBNull(3)){// And neither is this one; Iâm so excited.} if (!rdr.IsDBNull(4)){// This one isnât either? Really?} // ⦠if (!rdr.IsDBNull(723498234)){// And this oneâs not null either. Oh, what joy.}}Enter ??. Wait, what? ?? is an actual operator in C# and not a spelling mistake on your part? Iâve never heard of it in my entire life (okay, so maybe you did hear of it before, but I havenât, not âtil yesterday!).
Youâd code the ?? like this:
AwesomeObject someAwesomeObject = new AwesomeObject(); someAwesomeObject.AwesomeField = rdr.GetString(10) ?? string.Empty;To read more on the ?? operator, try this MSDN article.
I finally found out that the operator is called null coalescing operator and is available in C# 2005 only. Another reason C# rocks. ; -) Any questions?
The CheckBoxList, like most other web controls, makes my life a whole lot easier by automating what used to be a lot of drudge work. The CheckBoxList also, like most other web controls, spits out ugly, ugly markup that makes me incredibly pissed off. But the good thing in ASP .NET is that if you donât like the way something works, you can almost always inherit from the class and override the behavior, which is what weâre going to be doing with CheckBoxList.
Web custom controls have several benefits over user controls. To use a user control, you need to copy the .ascx file to each and every project that you you want to use it in, whereas web controls are compiled into .dll files, which means that to use them you just add a reference to the .dll file. Thereâs also the fact that user controls donât have designer support (admittedly not a big deal for me, since I work almost exclusively in the âSource View,â but I know lots of other people swear by the âDesign Viewâ); web custom controls, on the other hand, do.
Creating web custom controls can look like an untamable beast, but actually itâs quite easy. Start by clicking File » New » Project » Visual C# » Windows » Web Control Library. You can just as easily create a web custom control in whatever web project you happen to be working on, but because weâre interested in easy reuse, weâll put our extended CheckBoxList file in a web control library. Name it whatever you want.
Visual Studio will automatically create a file called WebCustomControl1.cs for you. Delete everything inside the class â we donât need it. Rename the file to something more appropriate, like UlCheckBoxList, and change all instances of WebCustomControl1 in the file to UlCheckBoxList (Visual Studio will probably automatically change the class name for you, but you also need to change the ToolboxData).
All web custom controls need to inherit from the WebControl class either directly or indirectly. The CheckBoxList control already inherits from this class. Since weâre interested in only the rendering part of the CheckBoxList weâll inherit from this one.
using System;using System.Collections.Generic;using System.ComponentModel;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls; namespace XhtmlWebControls{[ToolboxData("<{0}:UlCheckBoxList runat=server></{0}:UlCheckBoxList>")]public class UlCheckBoxList : CheckBoxList{protected override void Render(HtmlTextWriter writer){Controls.Clear(); string input = "<input id={0}{1}{0} name={0}{2}{0} type={0}checkbox{0} value={0}{3}{0}{4} />";string label = "<label for={0}{1}{0}>{2}</label>"; writer.WriteLine("<ul>"); for (int index = 0; index < Items.Count; index++){writer.Indent++;writer.Indent++; writer.WriteLine("<li>"); writer.Indent++; StringBuilder sbInput = new StringBuilder();StringBuilder sbLabel = new StringBuilder(); sbInput.AppendFormat(input,""",base.ClientID + "_" + index.ToString(),base.ClientID + "$" + index.ToString(),Items[index].Value,(Items[index].Selected ? " checked" : "")); sbLabel.AppendFormat(label,""",base.ClientID + "_" + i.ToString(),Items[index].Text); writer.WriteLine(sbInput.ToString());writer.WriteLine(sbLabel.ToString()); writer.Indentâ; writer.WriteLine("</li>"); writer.WriteLine(); writer.Indentâ;writer.Indentâ;} writer.WriteLine("</ul>");}}} Line 11: [ToolboxData("<{0}:UlCheckBoxList runat=server></{0}:UlCheckBoxList>")]
This tells Visual Studio what to write in the âSource Viewâ of the .aspx page in which weâre going to use the control. That is, if you drag and drop the control from the Toolbox onto the .aspx page.
Line 16: Controls.Clear();
The CheckBoxList has a single child control of type CheckBox, which is used to render all the checkboxes in the list. But as weâre going to be writing the HTML ourselves, we donât care about this control. So I cleared it, just in case having it around screws up something.
Line 18: string input = â<input id={0}{1}{0} name={0}{2}{0} type={0}checkbox{0} value={0}{3}{0}{4} />â;
Line 19: string label = â<label for={0}{1}{0}>{2}</label>â;
The html thatâs going to be outputted with some âstring format variablesâ thrown in. The formats are going to be replaced with the actual values later on (lines 35 - 47).
Line 25: writer.Indent++;
Makes the <li> tags and everything underneath appear one tab to the right (in the HTML source code) of the <ul> tag.
Line 38: base.ClientID + â_â + i.ToString(),
Line 39: base.ClientID + â$â + i.ToString(),
If your CheckBoxListâs name was âCheckBoxList1,â then the id and the name you see in the HTML source code would be âCheckBoxList1_xâ and âCheckBoxList1$x,â where x is the number of the checkbox in the list. I saw no reason to change this.
Compile the Web Control Library you just created. Go to the Toolbox, right-click on âGeneralâ (or whichever tab you want to put the class under) and select âChoose Itemsâ â In âChoose Toolbox Items,â under â.NET Framework Components,â select âBrowseâ and point to the .dll file of the class (should be located in the âDebugâ folder in the âBinâ folder of your Web Control Library folder). Click OK. And youâre good to go.