Grids and ASP.NET (vb)

Manually filling rows of data in ASP.NET controls can be a bit unintuitive. I’ll go over a few things I learned recently. I’m writing up this posting off the top of my head, so I can’t say for certain the code examples are correct in syntax.

Use the template field in your grid view as it’s the most flexible to deal with as apposed to using asp bind field tags or other means.

<asp:templatefield headertext="A Column">
		<a href="http://address"><%#Bind("dbField")%></a>

The example above is a column template field with the Bind() function call. Bind() is a special function that can be used to link data that the template field has access to within the grid row. You can also use Eval() which just prints the data and does not hard link the control and data like Bind() does. Also take note of the # in the asp tags <%# %> this is shorthand for printing out (displaying) the result of the asp code.

Another issue I’m came upon was trying to do some conditional display of data in a specific column of data.

<asp:templatefield headertext="A Column">
		<a href='<%#functionToCall(DataBinder.Eval(Container.DataItem, "dbField"))%>'><%="link text"%></a>

As you can see above, the href area of that anchor tag has quite a bit of ASP.NET code in it.

DataBinder.Eval(Container.DataItem, “dbField”):
This function is available in the template field control as well as the basic ones like Bind and Eval. It allows you to extract the current row of data from the database that is linked with the grid control you are in. The object Container.DataItem is a reference to the current row of database data (all fields which were in the select statement). So this function asks for the field “dbField” in the current row of data.

This is a function you define that gets passed the “dbField” data. Once you have data in the function you can easily do what you want with it. Your function should return a string value.

<%=”link text”%>:
In some circumstances it is necessary to not have a hard coded literal in a control. The compiler generates an error and doesn’t allow you to continue. In this instance, you can use the asp tag with a = that allows you to print out a literal string in quotes.

Help Support This Website:

Buying something through these Amazon affiliate links within 24 hours of clicking could help me out at no additional cost to you:
USA, UK, Canada, Germany, Spain, France, and Italy

Direct Donation Links:
Paypal, Buy Me A Coffee, or Ko-Fi

This entry was posted in General. Bookmark the permalink.