Skip to content

Adding a custom hyperlink to a DataGrid

February 2, 2012

Here is something I found out which allows you to add a custom made hyperlink in front of all the data items in a datagrid control:, initially here was the control I built that creates a HyperLink column used for the DataGrid.

// Now add the HyperLink column to view user
HyperLinkColumn userNameColumn = new HyperLinkColumn();
userNameColumn.DataTextField = “Username”;
userNameColumn.DataTextFormatString = “Username”;
userNameColumn.DataNavigateUrlField = “Username”;
userNameColumn.DataNavigateUrlFormatString = “user.aspx?user={0}”;
userNameColumn.Text = “view”;
userNameColumn.ItemStyle.Width = 50;

Notice here that I have set the DataTextField as the data context to the field Username, and set the text to be view, with a link to the user.aspx page with a querystring of user={0}.

I then found out that it displayed Username instead of the data which is linked to the field Username, so I removed the DataTextFormatString and that worked.

But having displayed the DataGrid, and seeing the next page, it displayed this custom column twice, and pondering as to why this occured, it had to be reusing the object tbl again, hence adding it to an existing item of DataGrid. What you therefore need to do is to create a new instance of DataGrid before doing the databinding.

Here is the final solution: –

// Create a Table and set its properties

tbl = new DataGrid();
tbl.ID = “tbl”;
tbl.CssClass = “dataTable”;

// Add the table to the placeholder control
PlaceHolder1.Controls.Add(tbl);

// Now add the HyperLink column to view user
HyperLinkColumn userNameColumn = new HyperLinkColumn();
userNameColumn.DataTextField = “Username”;
userNameColumn.DataTextFormatString = “Username”;
userNameColumn.DataNavigateUrlField = “Username”;
userNameColumn.DataNavigateUrlFormatString = “user.aspx?user={0}”;
userNameColumn.Text = “view”;
userNameColumn.ItemStyle.Width = 50;

tbl.Columns.Add(userNameColumn);

tbl.DataSource = dt;

tbl.DataBind();

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: