How to create dynamic Gridview?


Many times we have the requirement where we have to create columns dynamically.
This article describes you about the dynamic loading of data using the DataTable as the datasource.

Details of the Grid

Let?s have a look at the code to understand better.

Create a gridview in the page,

Drag and drop the GridView on to the page
Or

Manually type GridView definition in the page.


public partial class _Default : System.Web.UI.Page

{

#region constants

const string NAME = “NAME”;

const string ID = “ID”;

#endregion

protected void Page_Load(object sender, EventArgs e)

{

loadDynamicGrid();

}

private void loadDynamicGrid()

{

#region Code for preparing the DataTable

//Create an instance of DataTable

DataTable dt = new DataTable();

//Create an ID column for adding to the Datatable

DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));

dcol.AutoIncrement = true;

dt.Columns.Add(dcol);

//Create an ID column for adding to the Datatable

dcol = new DataColumn(NAME, typeof(System.String));

dt.Columns.Add(dcol);

//Now add data for dynamic columns

//As the first column is auto-increment, we do not have to add any thing.

//Let’s add some data to the second column.

for (int nIndex = 0; nIndex < 10; nIndex++)

{

//Create a new row

DataRow drow = dt.NewRow();

//Initialize the row data.

drow[NAME] = “Row-” + Convert.ToString((nIndex + 1));

//Add the row to the datatable.

dt.Rows.Add(drow);

}

#endregion

//Iterate through the columns of the datatable to set the data bound field dynamically.

foreach (DataColumn col in dt.Columns)

{

//Declare the bound field and allocate memory for the bound field.

BoundField bfield = new BoundField();

//Initalize the DataField value.

bfield.DataField = col.ColumnName;

//Initialize the HeaderText field value.

bfield.HeaderText = col.ColumnName;

//Add the newly created bound field to the GridView.

GrdDynamic.Columns.Add(bfield);

}

//Initialize the DataSource

GrdDynamic.DataSource = dt;

//Bind the datatable with the GridView.

GrdDynamic.DataBind();

}

}

Display image Dynamically on crystal report


This is very common requirement to display image on crystal report from database. Generally we store image path in database not whole image, because it increase the size of the database. I had the same requirement few days ago and search lot about the same. Finally I got the solution and decide to publish the post.

Here I put the code in C#, so just copy and paste the code and change it as per your need.

dsOrgDetails = objOrganisationMasterBal.GetOrganisationDetails();

if (dsOrgDetails.Tables[0].Rows.Count > 0)

{

DataRow drow;

dt.Columns.Add(“OrganizationImage”, System.Type.GetType(“System.Byte[]”));

dt.Columns.Add(“OrganizationName”, System.Type.GetType(“System.String”));

drow = dt.NewRow();

FileStream fs;

BinaryReader br;

if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + “OrganisationLogo\\” + dsOrgDetails.Tables[0].Rows[0][“Logo”].ToString()))

{

// open image in file stream

fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + “OrganisationLogo\\” + dsOrgDetails.Tables[0].Rows[0][“Logo”].ToString(), FileMode.Open);

}

else

{

// if photo does not exist show the nophoto.jpg file

fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + “OrganisationLogo\\noimages.jpg”, FileMode.Open);

}

br = new BinaryReader(fs);

// define the byte array of file length

byte[] imgbyte = new byte[fs.Length + 1];

// read the bytes from the binary reader

imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length)));

drow[0] = imgbyte;

//drow[0] = br.Read(imgbyte, 0, imgbyte.Length);

drow[“OrganizationName”] = dsOrgDetails.Tables[0].Rows[0][“OrganisationName”].ToString();

// add the image in bytearray

dt.Rows.Add(drow);

dt.AcceptChanges();

// add row into the data table

br.Close();

// close the binary reader

fs.Close();

}

First get the data from database, here I mean get the image path from the database. Then create DataTable for temporary conversation of path into image. In DataTable, create column of type System.Byte[].

Then create objects of FileStream and BinaryReader. Check that the file is exists or not, if exists then open the file in FileStream’s object. Then assign the FileStream’s object to the BinaryReader and go ahead as per the code.

Now, add the generated DataTable with Image in your DataSet which is assigned to the crystal report’s datasource.

Now, see at crystal report you can find the “OrganizationImage”¬† in Field Explorer of Crystal Report. Just Drag n Drop the image on crystal report. That’s it.

In some cases, at run time Image is not displayed on crystal report using above code. So for that do one thing.

Comment out this line : drow[0] = imgbyte;

and Uncomment this line : drow[0] = br.Read(imgbyte, 0, imgbyte.Length);

Now, compile the solution and run the report. Again Drag n Drop the image on report. And do the reverse, i mean Uncomment drow[0] = imgbyte this line and Comment  drow[0] = br.Read(imgbyte, 0, imgbyte.Length); this line, and re-compile the solution and run the report. You will get the image on your report.