11 Quick and Useful ASP.net Tips and Tricks
ten eleven tips and tricks I've collected while developing ASP.net applications. None of these are big enough to warrant their own article, but they are useful just the same. If you have any quick tips to add, I'd love to read about them in the comments below.
Insert <%# Container.DataItemIndex %> in a Gridview to display the current row. If you're displaying this on the screen, add + 1 to it since the container is zero-indexed.
Adding "return false" to the onClick function of an ASP button will prevent it from causing a postback.
<asp:Button ID="btnMyButton" runat="server" Text="Click Me" OnClientClick="alert('Woot'); return false;" />
When clicked, this will display an alert message without causing the page to postback afterward. You certainly could just use HTML buttons to get this same effect, but sometimes it's nice to have ASP buttons instead, even if just for consistency’s sake.
Get the version number of your app from AssemblyInfo.cs using this code:
string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
And if you want to get this information from a component to your web app, use this:
String version = System.Reflection.Assembly.GetCallingAssembly().GetName().Version.ToString();
When you create an ASP.net page that uses AJAX update panels and view the source of that page in Internet Explorer, the source you see is the source exactly as it was when the page was initially loaded. Changes made to values or controls on subsequent asynchronous postbacks are not reflected in the source you see. If you want to see how the source really looks after doing AJAX postbacks, use a tool like FireBug or the Visual Studio IDE (much improved for this in 2008).
Add Attributes to a header of a GridView control in the RowDataBound event with the following code:
if (e.Row.RowType == DataControlRowType.Header)
for (int i = 0; i < e.Row.Cells.Count - 1; i++)
e.Row.Cells[i].Attributes.Add("onclick", "alert('Stop clicking me!');");
Get just the name of the page you're at:
string currentPage = System.IO.Path.GetFileNameWithoutExtension(Request.PhysicalPath);
Get the length of the largest amount of text stored in a database field.
SELECT TOP (1) DATALENGTH(Summary) AS FieldLength
ORDER BY FieldLength DESC
To display just the date from the a DateTime field inside a GridView, inside a template column use:
<asp:Label ID="lblDate" runat="server" Text='&
This article has been view 1185 times.