This example is useful when you need to add new row in the gridview. Here to can add the link URL runtime.
Add a placeholder in the HTML page.
<asp:PlaceHolder ID="phGrid" runat="server"></asp:PlaceHolder>
Now create the gridview run time
private void BindGrid()
{
// Create new instance of gridview
GridView gvNew = new GridView();
gvNew.ID = "ItemGrid";
gvNew.SkinID = "ListView";
gvNew.Width = 300;
DataTable dt = Datasource();
if (dt.Columns.Count > 1)
{
// Assign RowDataBound handler. This will add link
// URL dynamically.
gvNew.RowDataBound += new
GridViewRowEventHandler(gvNew_RowDataBound);
gvNew.DataSource = dt;
gvNew.DataBind();
}
else
{
// Some Comments
}
phGrid.Controls.Add(gvNew);
}
Code behind Data Bound Function
protected void gvNew_RowDataBound(object sender,
GridViewRowEventArgs e)
{
int random = 1;
int count = e.Row.Cells.Count;
if (e.Row.RowType == DataControlRowType.DataRow)
{
string str = e.Row.Cells[0].Text;
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblEdit = new Label();
lblEdit.Text = " ";
Table tbl = new Table();
tbl = (Table)e.Row.Parent;
GridViewRow myRow = new GridViewRow(0, 0,
DataControlRowType.DataRow, DataControlRowState.Normal);
DataTable dt = new DataTable();
dt = (DataTable)this.dtOCCRateList;
for (int i = 0; i < count; i++)
{
TableCell myCell = new TableCell();
// need to create the edit hyperlink in the the footer
if (i == 0)
{
// leave blank
myCell.Controls.Add(new LiteralControl(""));
}
else
{
// create the image and hyperlink
HyperLink editLink = new HyperLink();
editLink.ID = "editLink" + random;
// set the image url
editLink.ImageUrl =
"~/library/images/ico-edit.gif";
// set the navigate url
editLink.NavigateUrl =
"~/Default.aspx?Id=" + dt.Rows[0][i].ToString()
+ "&PId=" + AssetId.ToString();
// now add this hyperlink in the table cell
myCell.Controls.Add(editLink);
// add delete
HyperLink delLink = new HyperLink();
delLink.ID = "delLink" + random;
random++;
delLink.ImageUrl = "~/Library/images/delete.gif";
// set the navigate url
delLink.NavigateUrl = "~/Default.aspx?Id=" +
dt.Rows[0][i].ToString() +
"&PId=" + AssetId.ToString();
myCell.Controls.Add(new LiteralControl(" "));
myCell.Controls.Add(delLink);
}
myRow.Cells.Add(myCell);
tbl.Rows.Add(myRow);
}
}
}