I build a gridview at runtime that works great. Now, I have to add a linkbutton to the gridview at runtime (the linkbutton will allow display a modal popup for editing). The code below is not working. I use similar code to add an imagecontrol to the gridview and it works. Can anyone help?
// Add the edit link
TemplateField tfEdit = new TemplateField();
tfEdit.ShowHeader = false;
LinkButton lb = new LinkButton();
lb.ID = "lnkEditProduct";
lb.Text = "Edit Item";
lb.CommandArgument = "<%# Bind('itemID') %>";
lb.CommandName = "EditProduct";
lb.CausesValidation = false;
gvResults.Columns.Add(lb);
Thank you!
KentPosted May 4, 2009, 10:38 AM
For example:
gvResults.Columns.Clear; // Clear all columns from the gridview then I begin to add columns as needed
bFld = new BoundField();bFld.DataField = "brandName";
bFld.HeaderText = "Brand";
bFld.SortExpression = "brandName";
gvResults.Columns.Add(bFld);
But, this code does not work:
LinkButton lb = new LinkButton();
lb.ID = "lnkEditProduct";lb.Text = "Edit Item";
lb.CommandName = "EditProduct";
lb.CausesValidation = false;
gvResults.Columns.Add(lb); // the error here is "cannot convert webcontrols.linkbotton to webcontrol.datacontrolfield"
Thanks again!
Pramod Kumar NandagiriPosted May 1, 2009, 8:55 AM
Niradhip ChakrabortyPosted May 1, 2009, 5:35 AM
Hi,
Instead of adding a control dynamically during data-binding, why don't you rather use a ButtonColumn in your GridView? This will create the buttons for you, which will fire an OnRowCommand event when clicked, allowing you to add your objects to your session list (the CommandName property of the EventArgs object of the event will contain the command of the button clicked and CommandArgument will contain the row index).
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExpertsExchange._Default" %>
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.w3.org/1999/xhtml" >
/* Default.aspx.cs : Code-behind */
namespace ExpertsExchange
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int[] dataSource = new int[] { 1, 1, 2, 3, 5, 8, 13 };
gridView1.DataSource = dataSource;
gridView1.DataBind();
}
}
protected void gridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToSessionList")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
if (Session["SessionList"] == null)
Session["SessionList"] = new List
(Session["SessionList"] as List
}
}
}
}