Search This Blog

Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Tuesday, January 26, 2010

Showing gridview when no records present

Here is an easy solution to get a GridView to show headers when there are no records to show.

Code snippet:

DataTable dt = getResults(); //getResults would query your datasource and return a datatable

if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.Databind();
}
else //part that generates the Gridview with headers only
{
dt.Rows.Add(); //adds blank row to table
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Rows[0].Visible = false; //makes blank row invisible
GridView1.Rows[0].Controls.Clear(); //removes any controls for row
}

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";
}