Search This Blog

Showing posts with label LinkButton. Show all posts
Showing posts with label LinkButton. Show all posts

Tuesday, December 1, 2009

Custom Link Buttons In Gridview

There have been times in my job, where a customized link button in a gridview was needed. While there are probably several ways to do this, the following is the best way to do it that I have found. In my case, I needed the link button to change text, and also change command name, based off of data from a query.

What I did was when creating the binding of the datasource to the gridview in codebehind, I added a datakey that I wanted to key off of.

gv.DataKeyNames = new string[] { "excluded" };


Then in the RowDataBound event, I have the following code within it. Basically it looks at the value I'm keying off of, and if it is a 1, then does one routine, else it does another. In the routine, it gets the LinkButton control from the cell, and then sets the text, forecolor, and command name.

if (Convert.ToString(gvEvents.DataKeys[e.Row.RowIndex].Values["excluded"].ToString()) == "1")
{
LinkButton lb = (LinkButton)e.Row.Cells[10].Controls[0];
lb.Text = "Include";
lb.ForeColor = System.Drawing.Color.Black;
lb.CommandName = "include";
}
else
{
LinkButton lb = (LinkButton)e.Row.Cells[10].Controls[0];
lb.Text = "Exclude";
lb.ForeColor = System.Drawing.Color.Black;
lb.CommandName = "exclude";
}