I have Gridview set to autogenerate columns=true i have created some dynamic text boxes for some columna nd footer now ehn i click on footer button gridview rowcomand event is not fired, to fire this command i have to bind the gridview again but when i bind my values which i have changes in textboxes gone..
following is my code rowdatabound event
protected void grdMaterialPercentage_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (grdMaterialPercentage.AutoGenerateColumns == true)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Visible = false;
if (DataBinder.Eval(e.Row.DataItem, "AgentName").ToString() != string.Empty)
{
int i = 0;
foreach (TableCell c in e.Row.Cells)
{
if (i >= 3)
{
TextBox tb = new TextBox();
tb.Text = c.Text;
tb.ID = "txtbox" + i.ToString();
tb.Style.Add("Width", "25px");
tb.Style.Add("Height", "15px");
c.Controls.Clear();
c.Controls.Add(tb);
}
i++;
}
}
else
{
e.Row.Visible = false;
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Visible = false;
int j = 0;
foreach (TableCell c in e.Row.Cells)
{
if (j >= 3)
{
DataRow dr = dt.Rows[dt.Rows.Count - 1];
LinkButton btn = new LinkButton();
btn.ID = "FooterButton" + j.ToString();
btn.CommandName = j.ToString();
btn.Text = "Save" + dr[j - 1].ToString();
btn.CssClass = "button";
btn.Style.Add("align", "center");
btn.CommandArgument = dr[j - 1].ToString();
btn.OnClientClick = "return ValidateTotalPercentage('" + j + "')";
c.Controls.Clear();
c.Controls.Add(btn);
} j++;
}
}
}
}
I suggest you use a tool such as Firebug to see what is happening under the hood with your Javascript when you click the link on the grid. This is what I would do in your shoes.
Related
How to remove last row selected item in dropdown add button is clicked gridview asp.net.
GridViewRow gvrow = (GridViewRow)((Control)e.CommandSource).NamingContainer;
if (e.CommandName == "Add")
{
ddt = CreateDt();
int j = 0;
foreach (GridViewRow gr in GvPatientAccomDtls.Rows)
{
ddt.Rows.Add();
ddt.Rows[j]["TreatmentCode"] = ((DropDownList)gr.FindControl("ddlTreatment")).SelectedValue;
ddt.Rows[j]["Days"] = ((TextBox)gr.FindControl("txtDays")).Text;
ddt.Rows[j]["Cost"] = ((TextBox)gr.FindControl("txtCost")).Text;
j++;
}
ddt.Rows.Add();
GvPatientAccomDtls.DataSource = ddt;
GvPatientAccomDtls.DataBind();
}
you can handle with RowDataBound Event
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var thisRow = (DataRowView)e.Row.DataItem;
var source = thisRow.DataView;
var lastRowIndex = e.Row.DataItemIndex -1;
DataRowView lastRow = null;
var ddl = (DropDownList)e.Item.FindControl("ddl");
DropDownList ddlLast = null;
if(lastRowIndex>=0){
lastRow = source[lastRowIndex];
ddlLast = (DropDownList)((GridView)sender).Rows[lastRowIndex].FindControl("ddl");
//remove the items of this ddl according to the items of the last dll
}
}
}
OK. I've long used this site as a reference, but I've now hit a wall of my own.
I am creating a custom server control which inherits from the System.Web.UI.WebControls.GridView class. It's purpose is simply to display a grid with a very defined format. It binds and loads the data fine, but trying to activate any of the paging throws an exception saying "Multiple controls with the same ID 'lblHdrText_2' were found. FindControl requires that controls have unique IDs.".
I could just throw the event out to the user and let them do the paging, but one of the goals was to have this control be able to handle its own paging, just like the GridView control already does.
I'm having the same problem for sorting and altering the page size as well. Basically anytime I call "DataBind" within the control after it has already been rendered.
Here's the code to handle those events:
protected void OnFirstPageClicked(EventArgs e)
{
if (this.FirstPageClicked != null)
this.FirstPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(0);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = 0;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnLastPageClicked(EventArgs e)
{
if (this.LastPageClicked != null)
this.LastPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageCount - 1);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = this.PageCount - 1;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnPreviousPageClicked(EventArgs e)
{
if (this.PageIndex > 0)
{
if (this.PreviousPageClicked != null)
this.PreviousPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex--;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnNextPageClicked(EventArgs e)
{
if (this.PageIndex < this.PageCount - 1)
{
if (this.NextPageClicked != null)
this.NextPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex++;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnPageSizeChanged(EventArgs e)
{
this.RefreshData();
if (this.PageSizeChanged != null)
this.PageSizeChanged.Invoke(this, e);
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
}
private void RefreshData()
{
this.DataBind();
}
private void imgPg_OnCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "FirstPage":
this.OnFirstPageClicked(EventArgs.Empty);
break;
case "LastPage":
this.OnLastPageClicked(EventArgs.Empty);
break;
case "PrevPage":
this.OnPreviousPageClicked(EventArgs.Empty);
break;
case "NextPage":
this.OnNextPageClicked(EventArgs.Empty);
break;
}
}
private void drpPageSz_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList drpPgSz = (sender as DropDownList);
if (drpPgSz != null)
{
this.PageSize = int.Parse(drpPgSz.SelectedValue);
this.OnPageSizeChanged(e);
}
else
throw new Exception("Unable to determine page size: cannot cast sender as DropDownList.");
}
The actual event handlers are at the bottom. The "RefreshData" method is just there because I was experimenting with different ways of clearing the controls from the grid before I called "DataBind". So far, everything I've tried results in the entire grid not rendering after postback.
I am doing quite a bit with the Render and CreateChildControls, but the header generation itself is completely internal to the System.Web.UI.WebControls.GridView control. Here's my rendering code, if it helps at all:
protected override void OnPreRender(EventArgs e)
{
Control link = this.Page.Header.FindControl("CustomGridViewCss");
if (link == null)
{
System.Web.UI.HtmlControls.HtmlLink newLink = new System.Web.UI.HtmlControls.HtmlLink();
newLink.ID = "CustomGridViewCss";
newLink.Attributes.Add("href", this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.style.CustomGridView.css"));
newLink.Attributes.Add("type", "text/css");
newLink.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(newLink);
}
base.OnPreRender(e);
this.EnsureChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
if (this._imgFPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgFPg.UniqueID);
if (this._imgPrevPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgPrevPg.UniqueID);
if (this._imgNextPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgNextPg.UniqueID);
if (this._imgLastPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgLastPg.UniqueID);
if (this._drpPageSz != null)
this.Page.ClientScript.RegisterForEventValidation(this._drpPageSz.UniqueID);
if (this.HeaderRow != null)
for (int i = 1; i < this.HeaderRow.Cells.Count - 2; i++)
if (i < this.Columns.Count && this.Columns[i] is SortableField && ((this.Columns[i] as SortableField).ShowSort))
{
ImageButton img = (this.HeaderRow.Cells[i].FindControl("imgSort_" + i.ToString()) as ImageButton);
if (img != null)
this.Page.ClientScript.RegisterForEventValidation(img.UniqueID);
}
base.Render(writer);
}
protected override Table CreateChildTable()
{
this.PagerSettings.Visible = false;
this.GridLines = GridLines.None;
Table tbl = base.CreateChildTable();
tbl.Attributes.Add("name", this.UniqueID);
return tbl;
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
this.GridLines = GridLines.None;
int iCount = base.CreateChildControls(dataSource, dataBinding);
// Modify footer row
System.Web.UI.WebControls.GridViewRow ftr = this.FooterRow;
// NOTE: We're modifying the footer first, because we're looking at the
// total number of rows in the header for the ColSpan property we
// use in the footer and we want the row count *before* we modify
// the header.
ftr.Cells.Clear();
this.BuildFooter(this.FooterRow);
// Modify Header Row
System.Web.UI.WebControls.GridViewRow hdr = this.HeaderRow;
hdr.CssClass = "GridViewHeader";
for (int c = 0; c < hdr.Cells.Count; c++)
{
hdr.Cells[c].CssClass = "GridViewHeaderTC";
if (c > 0)
hdr.Cells[c].Style.Add("border-left", "solid 1px #ccccd3");
if (c < this.Columns.Count && this.Columns[c] is SortableField && ((this.Columns[c] as SortableField).ShowSort))
{
hdr.Cells[c].Controls.Clear();
Label lblHdrText = new Label();
lblHdrText.ID = "lblHdrText_" + c.ToString();
lblHdrText.Text = hdr.Cells[c].Text;
hdr.Cells[c].Controls.Add(lblHdrText);
ImageButton imgSort = new ImageButton();
imgSort.ID = "imgSort_" + c.ToString();
imgSort.CssClass = "GridViewHeaderSort";
imgSort.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.Sort.png");
imgSort.AlternateText = "";
imgSort.CommandArgument = (this.Columns[c] as BoundField).DataField;
imgSort.CommandName = "Sort";
imgSort.Command += new CommandEventHandler(this.imgSort_OnCommand);
hdr.Cells[c].Controls.Add(imgSort);
imgSort.Attributes.Add("name", imgSort.UniqueID);
}
}
TableCell tdTL = new TableCell();
tdTL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTL.CssClass = "GridViewHeaderTL";
hdr.Cells.AddAt(0, tdTL);
TableCell tdTR = new TableCell();
tdTR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTR.Style.Add("border-left", "1px solid #ccccd3;");
tdTR.CssClass = "GridViewHeaderTR";
hdr.Cells.Add(tdTR);
// Modify individual rows
for (int i = 0; i < this.Rows.Count; i++)
{
System.Web.UI.WebControls.GridViewRow tr = this.Rows[i];
tr.CssClass = (i % 2 == 0) ? "GridViewLineAlt" : "GridViewLine";
for (int c = 0; c < tr.Cells.Count - 1; c++)
tr.Cells[c].Style.Add("border-right", "solid 1px #ccccd3");
TableCell tdL = new TableCell();
tdL.CssClass = "GridViewLineLeft";
tr.Cells.AddAt(0, tdL);
TableCell tdR = new TableCell();
tdR.CssClass = "GridViewLineRight";
tr.Cells.Add(tdR);
}
return iCount;
}
protected void BuildFooter(GridViewRow tr)
{
TableCell tdBL = new TableCell();
tdBL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBL.CssClass = "GridViewFooterBL";
tr.Cells.Add(tdBL);
int colCount = this.HeaderRow.Cells.Count;
TableCell td = new TableCell();
td.ID = "tdFooterControls";
td.CssClass = "GridViewFooterBC";
td.ColumnSpan = colCount;
this._spanPgBtns = new Label();
this._spanPgBtns.ID = "spanPgButtons";
this._spanPgBtns.Style.Add("float", "right");
this._spanPgBtns.Style.Add("margin-right", "20px");
this._imgFPg = new ImageButton();
this._imgFPg.ID = "imgFPg";
this._imgFPg.CssClass = "FirstPg";
this._imgFPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.FstPg.png");
this._imgFPg.ImageAlign = ImageAlign.Middle;
this._imgFPg.CommandName = "FirstPage";
this._imgFPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgFPg);
this._imgPrevPg = new ImageButton();
this._imgPrevPg.ID = "imgPrevPg";
this._imgPrevPg.CssClass = "PrevPg";
this._imgPrevPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.PrevPg.png");
this._imgPrevPg.ImageAlign = ImageAlign.Middle;
this._imgPrevPg.CommandName = "PrevPage";
this._imgPrevPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgPrevPg);
Label lblPageNum = new Label();
lblPageNum.ID = "lblPageNum";
lblPageNum.Width = new Unit("50px");
lblPageNum.Text = string.Format("{0} / {1}", this.PageIndex + 1, this.PageCount);
lblPageNum.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
this._spanPgBtns.Controls.Add(lblPageNum);
this._imgNextPg = new ImageButton();
this._imgNextPg.ID = "imgNextPg";
this._imgNextPg.CssClass = "NextPg";
this._imgNextPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.NextPg.png");
this._imgNextPg.ImageAlign = ImageAlign.Middle;
this._imgNextPg.CommandName = "NextPage";
this._imgNextPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgNextPg);
this._imgLastPg = new ImageButton();
this._imgLastPg.ID = "imgLastPg";
this._imgLastPg.CssClass = "LastPg";
this._imgLastPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.LstPg.png");
this._imgLastPg.ImageAlign = ImageAlign.Middle;
this._imgLastPg.CommandName = "LastPage";
this._imgLastPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgLastPg);
td.Controls.Add(this._spanPgBtns);
Label spanPageSz = new Label();
spanPageSz.ID = "spanPageSz";
spanPageSz.Style.Add("margin-left", "20px");
this._drpPageSz = new DropDownList();
this._drpPageSz.ID = "drpPageSzSelect";
this._drpPageSz.AutoPostBack = true;
this._drpPageSz.SelectedIndexChanged += new EventHandler(drpPageSz_SelectedIndexChanged);
this._drpPageSz.Items.Add(new ListItem("10", "10"));
this._drpPageSz.Items.Add(new ListItem("25", "25"));
this._drpPageSz.Items.Add(new ListItem("50", "50"));
this._drpPageSz.Items.Add(new ListItem("100", "100"));
spanPageSz.Controls.Add(this._drpPageSz);
td.Controls.Add(spanPageSz);
Label lblRecVis = new Label();
lblRecVis.ID = "lblRecordsCount";
lblRecVis.Style.Add("margin-left", "20px");
lblRecVis.Text = string.Format("Displaying {0} of {1} records.", Math.Min(this.PageSize, this.Rows.Count - (this.PageIndex * this.PageSize)), this.Rows.Count);
lblRecVis.Text = "Total Record Display";
td.Controls.Add(lblRecVis);
tr.Cells.Add(td);
TableCell tdBR = new TableCell();
tdBR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBR.CssClass = "GridViewFooterBR";
tr.Cells.Add(tdBR);
this._imgFPg.Attributes.Add("name", this._imgFPg.UniqueID);
this._imgPrevPg.Attributes.Add("name", this._imgPrevPg.UniqueID);
this._imgNextPg.Attributes.Add("name", this._imgNextPg.UniqueID);
this._imgLastPg.Attributes.Add("name", this._imgLastPg.UniqueID);
this._drpPageSz.Attributes.Add("name", this._drpPageSz.UniqueID);
}
I'm only about 6/10 on custom server controls, so I'm sure there's at least one thing I'm doing wrong here :)
Thanks in advance for any help!
OK. I finally found a reference and answered my own question. The trick is in overriding the "PerformSelect" method and handling DataSource vs DataSourceID there.
Details on how to do this can be found on this MSDN page:
http://msdn.microsoft.com/en-us/library/ms366539(v=vs.90).aspx
Look for the section titled "Initiate Data Retrieval" a little over half-way down.
I was trying to create a table dynamically and put textboxes in it. Here in the following code, i was trying to create a textbox with a distinct name for each k. But only the last value of k is getting displayed in the textbox. I was wondering how i could give a name to Textbox so all are shown.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Replace this line
dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
With
dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
I assume you are talking about ID like below.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
txtCompanyName.ID = Guid.NewGuid().ToString("N");
tc.Controls.Add(txtCompanyName);
}
I think you may have meant to do this:
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
//txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols-1 ["NewCompanyName"].ToString();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Surely this will work and it is easy to understand
protected void Page_Load(object sender, EventArgs e)
{
button1();
}
protected void Page_Init(object sender, EventArgs e)
{
try
{
Label lbl = new Label();
lbl.ID = "lbl_label";
lbl.Text = "Enter the values";
form1.Controls.Add(lbl);
TextBox tb = new TextBox();
tb.ID = "tbx_textbox";
form1.Controls.Add(tb);
Button bt = new Button();
bt.ID = "bt_button";
bt.Text = "click";
form1.Controls.Add(bt);
}
catch (Exception ex) { }
}
public void button1()
{
Table table = new Table();
TableRow row = null;
TableCell cell = null;
TextBox tbx1 = this.Page.FindControl("tbx_textbox") as TextBox;
try
{
int a = int.Parse(tbx1.Text);
for (int i = 0; i < a; i++)
{
row = new TableRow();
cell = new TableCell();
TextBox tx = new TextBox();
tx.ID = "box" + i.ToString();
cell.Controls.Add(tx);
row.Cells.Add(cell);
table.Rows.Add(row);
form1.Controls.Add(table);
}
}
catch (Exception ex) { }
finally
{
table = null;
}
}
I am able to create BoundFields and Footer-rows dynamically like this in my GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateGridView();
}
}
private void CreateGridView()
{
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
int colCount = 1;
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
//boundField.FooterText = "---";
if (colCount == 3 || colCount == 5)
{
boundField.ReadOnly = true;
}
GridView1.Columns.Add(boundField);
colCount++;
}
GridView1.ShowFooter = true;
GridView1.DataSource = dataTable;
GridView1.DataBind();
GridViewRow footerRow = GridView1.FooterRow;
Button b = new Button();
b.Text = "Add New";
int i = 0;
footerRow.Cells[i].Controls.Add(b);
foreach (DataColumn c in dataTable.Columns)
{
++i;
TextBox tb = new TextBox();
footerRow.Cells[i].Controls.Add(tb);
}
}
....................................
....................................
....................................
}
But the problem is, when I click the "Add New" - button, it disappears instantly. And, also I am unable to add any event handler to it. Or intercept its actions like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//We can get cell data like this
string id = selectedRow.Cells[1].Text;
string isbn = selectedRow.Cells[2].Text;
//This is necessary to GridView to be showed up.
CreateGridView();
}
else if (e.CommandName == "Update")
{
LinkButton updateButton = (LinkButton)e.CommandSource;
DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;
GridViewRow gvr = (GridViewRow)dcfc.Parent;
//The update...................
//Update grid-data to database
UpdateDataInTheDatabase(gvr.Cells[1].Controls);
//Grid goes back to normal
GridView1.EditIndex = -1;
//This is necessary to GridView to be showed up.
CreateGridView();
}
}
One more thing, I have seen some solutions that suggests to handle the GridView's rowBound event. But I need to do it from within Page_load event handler, or in, GridView1_RowCommand event handler.
Dynamically created controls mus be re-created on every postback. Your "Add New" button causes a postback so the dynamically created footer disappears. Is there a reason this grid has to be created dynamically? From the code you posted it appears that you could do this in markup instead. If not, you'll have to re-create the dynamic controls on every postback.
Edited to add:
I played with this a little bit and what's below works in that the grid doesn't disappear and events are handled, but it doesn't actually do anything. Hope this helps.
Markup:
<p><asp:Literal ID="Literal1" runat="server" /></p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}
Move your code from Page_Load to Page_Init. Things added in the Page_Load last only for the lifecycle of one postback.
You'd then be able to add eventhandlers, intercept events etc.
i have set enableviewstate property of linkbutton and label to true.also regenrating same buttons on postback in pageload event handler.but m not able to call onclick event handler of linkbutton.can u please tell me what is problem with code?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<LinkButton> listOfLinkButton = Session["ListOfLinkButton"] as List<LinkButton>;
List<Label> listOfLabel = Session["ListOfLabel"] as List<Label>;
if(listOfLabel!=null && listOfLinkButton!=null)
{
for (int i = 0; i < listOfLinkButton.Count; i++)
{
PlaceHolder1.Controls.Add(listOfLinkButton[i]);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(listOfLabel[i]);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
LinkButton linkButton = sender as LinkButton;
Response.Redirect(linkButton.Attributes["LinkUrl"]);
}
protected void Button1_Click1(object sender, EventArgs e)
{
List<LinkButton> listOfLinkButton = new List<LinkButton>();
List<Label> listOfLabel = new List<Label>();
Rss rssDocumentObj = RssFileReader.GetRssDocumentData(TextBox1.Text);
for (int j = 0; j < rssDocumentObj.ListOfChannel.Count; j++)
{
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonForChannelDynamicInPlaceHolder1Id" + j;
linkButton.EnableViewState = true;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 18;
linkButton.Font.Underline = true;
linkButton.Text = rssDocumentObj.ListOfChannel[j].ChannelTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl", rssDocumentObj.ListOfChannel[j].ChannelLink.InnerText);
linkButton.Attributes.Add("onmouseover", "this.style.color = '#006699'");
linkButton.Attributes.Add("onmouseout", "this.style.color = '#0000ff'");
PlaceHolder1.Controls.Add(linkButton);
listOfLinkButton.Add(linkButton);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Label label = new Label();
label.ID = "LabelForChannelDynamicInPlaceHolder1Id" + j;
label.EnableViewState = true;
label.ForeColor = Color.DarkSlateGray;
label.Text = rssDocumentObj.ListOfChannel[j].ChannelDescription.InnerText;
PlaceHolder1.Controls.Add(label);
listOfLabel.Add(label);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
for (int i = 0; i < rssDocumentObj.ListOfChannel[j].ListOfItem.Count; i++)
{
LinkButton linkButtonForItem = new LinkButton();
linkButtonForItem.ID = "LinkButtonDynamicInPlaceHolder1Id" + j + " " + i;
linkButtonForItem.EnableViewState = true;
linkButtonForItem.ForeColor = Color.Blue;
linkButtonForItem.Font.Bold = true;
linkButtonForItem.Font.Size = 14;
linkButtonForItem.Font.Underline = false;
linkButtonForItem.Text = rssDocumentObj.ListOfChannel[j].ListOfItem[i].ItemTitle.InnerText;
linkButtonForItem.Click += new EventHandler(LinkButton_Click);
linkButtonForItem.Attributes.Add("LinkUrl", rssDocumentObj.ListOfChannel[j].ListOfItem[i].ItemLink.InnerText);
linkButtonForItem.Attributes.Add("onmouseover", "this.style.color = '#006699'");
linkButtonForItem.Attributes.Add("onmouseout", "this.style.color = '#0000ff'");
PlaceHolder1.Controls.Add(linkButtonForItem);
listOfLinkButton.Add(linkButtonForItem);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Label labelForItem = new Label();
labelForItem.ID = "LabelDynamicInPlaceHolder1Id" + i;
labelForItem.EnableViewState = true;
labelForItem.ForeColor = Color.DarkGray;
labelForItem.Text = rssDocumentObj.ListOfChannel[j].ListOfItem[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(labelForItem);
listOfLabel.Add(labelForItem);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Session["ListOfLinkButton"] = listOfLinkButton;
Session["ListOfLabel"] = listOfLabel;
}
}
}
}
You are making assumptions about what aspects of that button is saved in session. Try adding the event to the button again when you restore from session state during your page load.
I got my solution by assigning event-handler to button again after retrieving it from session, but I could not understand why I need to assign it again, when its already assigned in stored session variable.