Customising a ListControl's DataTextField value

3.67 (3 votes)

The DataTextField property is used with ListControls - RadioButtonList, CheckBoxList etc to specify a field in the DataSource property to display as the items of the list in the list control. Sometimes, however, you don't want just the value from one database field to appear in the list, and there are a couple of ways to achieve this, depending on what you want to do.

Concatenation

If the value you would like to appear can be derived from multiple database fields, you can use concatentation in the SQL statement to create an expression. For example, a common requirement is to provide a count of items in a category in brackets (parentheses) after the name of a category, eg Beverages (12). Using the Northwind database (and the Access version is good enough for this demonstration), the following is the SQL that would achieve such an outcome:

SELECT Categories.CategoryID, 
Categories.CategoryName & ' (' & Count(Products.ProductID) & ')' As CountOfCategories  
FROM Categories 
INNER JOIN Products 
ON Categories.CategoryID = Products.CategoryID  
GROUP BY Categories.CategoryID, Categories.CategoryName

CountOfCategories is the expression that holds the value we want, which comprises the CategoryName value, followed by an opening bracket, concatented with the value from Count(Products.ProductID) for each CategoryName and finished off with a closing bracket. It's a simple job to apply this value to the DataTextField property:

[c#]
string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connect);
string query = @"SELECT Categories.CategoryID, 
		Categories.CategoryName & ' (' & Count(Products.ProductID) & ')' 
                As CountOfCategories  
		FROM Categories 
		INNER JOIN Products 
		ON Categories.CategoryID = Products.CategoryID  
		GROUP BY Categories.CategoryID, Categories.CategoryName";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
OleDbDataReader rdr = cmd.ExecuteReader();
CheckBoxList1.DataSource = rdr;
CheckBoxList1.DataTextField = "CountOfCategories";
CheckBoxList1.DataValueField = "CategoryID";
CheckBoxList1.DataBind();
rdr.Close();
conn.Close();
[VB]
Dim query As String = "SELECT Categories.CategoryID," & _ 
		"Categories.CategoryName & ' (' & Count(Products.ProductID) & ')' " & _
                "As CountOfCategories" & _   
		"FROM Categories " & _ 
		"INNER JOIN Products" & _ 
		"ON Categories.CategoryID = Products.CategoryID" & _   
		"GROUP BY Categories.CategoryID, Categories.CategoryName"
Dim connect As String 
connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Dim conn As New OleDbConnection(connect)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
CheckBoxList1.DataSource = rdr
CheckBoxList1.DataTextField = "CountOfCategories"
CheckBoxList1.DataValueField = "CategoryID"
CheckBoxList1.DataBind()
rdr.Close()
conn.Close()

PreRender

A Control's PreRender event occurs after a control has been loaded into memory on the web server, but before it is rendered to the html stream. so it is at this point during the page's lifecycle that any final tweaks can be made to the properties of a control. Consequently, if you want to customise the DataTextField values, this is when you do it. In the example below, each of the items in the list are enumerated, and that enumeration is applied to the DataTextField value. First, though, the DataTextField needs to be populated:

[C#]
string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
string query = @"SELECT CategoryID, CategoryName FROM Categories";
OleDbConnection conn = new OleDbConnection(connect);
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
OleDbDataReader rdr = cmd.ExecuteReader();
CheckBoxList1.DataSource = rdr;
CheckBoxList1.DataTextField = "CategoryName";
CheckBoxList1.DataValueField = "CategoryID";
CheckBoxList1.DataBind();
rdr.Close();
conn.Close();
[VB]
Dim connect As String 
connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Dim query As String = "SELECT CategoryID, CategoryName FROM Categories"
Dim conn As New OleDbConnection(connect)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
CheckBoxList1.DataSource = rdr
CheckBoxList1.DataTextField = "CategoryName"
CheckBoxList1.DataValueField = "CategoryID"
CheckBoxList1.DataBind()
rdr.Close()
conn.Close()

Now we create an event handler for the CheckBox's PreRender event. Within the handler, we define an integer and set it's value to 1. Iterating through the collection of ListItems, we obtain the Text property then modify it by having the value of the integer variable prepended. Then the integer value is advanced by 1.

[C#]
protected void CheckBoxList1_PreRender(object sender, EventArgs e)
{
  int i = 1;
  foreach (ListItem item in CheckBoxList1.Items)
  {
    string curval = item.Text;
    item.Text = i.ToString() + ". " + curval;
    i++;            
  }
}
[VB]
Protected Sub CheckBoxList1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) _
	Handles CheckBoxList1.PreRender
  Dim i As Integer = 1
  For Each item As ListItem In CheckBoxList1.Items
    Dim curval As String = item.Text
    item.Text = i.ToString() & ". " & curval
    i = i + 1
  Next
End Sub

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 10030

0 Comments

Recent Comments

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...

Mau 06/06/2017 08:58
In response to Razor Pages - The Elevator Pitch
I am missing the razor view code. Thank you for your article. Design pattern should improve the of...

Obinna Okafor 26/05/2017 16:16
In response to Razor Pages - The Elevator Pitch
Thank you for this wonderful piece, Mike. I need more of these...Keep them coming - anything more...

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...