Wednesday, October 28, 2009

Add Image in between Rows of a GridView using C#

again i come up with some new tips on Gridview , there are lots many things are there in Gridview . now my this article is describe you how to add the image on Gridivew, you can say after perticular records then you can use " OnRowDataBound " Property or " onRowCreated " like first 5 records then some distinguished between next 5 records like that.
here are the stpes how you can do that.

1. Create one Application
2. Add the Gridview control on a page ,also add the data source for same ,and just simply link it with some sample table
3. consider below is your Gridview code


<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="CustomerID"
runat="server" OnRowDataBound="GridView1_RowDataBound" AllowSorting="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>


4. now suppose if i want to add new row which is background , then i have to add Gridview_RowDataBound event , this will enable you to provide the Event-Handling method which will perform the Custom routine option. that can be like modiffy the row, add the new record into the row and so on.now for that we are adding page level varible call pSize which will hold the Row position where we want to add that image column, with same also add that image to your Gridview
below code will help you .



static int pSize;

protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
pSize = 0;
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

TableCell TabCell = new TableCell();
Image img = new Image();
img.ImageUrl = "Photo.gif";
TabCell.Controls.Add(img);

GridView gView = (GridView)sender;
int colSpan = gView.Columns.Count;
TabCell.Attributes["ColSpan"] = colSpan.ToString();

GridViewRow gRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);

gRow.Cells.Add(TabCell); // add the cells to the gridviewrow

Table newtbl = (Table)e.Row.Parent;

if(pgSize == 0)
pgSize = GridView1.PageCount / 2;

if (Convert.ToDouble(e.Row.DataItemIndex + 1) / Convert.ToDouble(pgSize) == 1.0)
{
newtbl.Controls.AddAt(gView.Controls[0].Controls.Count, gRow);
// add 10 to the pgsize so that the image can be displayed
// at rows 5, 15, 25 and so on..
pgSize = pgSize + 10;
}



here you can see how its look like:



hope this example will helps you .

No comments:

Post a Comment