New to dynamic controls, but until now I have been creating them successfully in a
template field in my gridview, recently switched from a hyperlink to a link button
and had to make some changes but still not working
In my page I have the following code (abridged to salient parts)
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
...
...
TemplateField tf = new TemplateField();
tf.HeaderText = "Action";
tf.ItemTemplate = new AssignPage.MyTemplate(..., mylb);
GridView1.Columns.Add(tf);
protected void Page_PreInit(object sender, EventArgs e)
{
LinkButton lb = new LinkButton();
lb.Text = "AssignAll";
lb.Command += new CommandEventHandler(AssignAll_Click);
lb.CommandName = "XXX";
this.mylb = lb;
protected void AssignAll_Click(object sender, CommandEventArgs e)
{
string[] arg = new string[2]; // BREAK POINT HERE
arg = e.CommandArgument.ToString().Split(';');
...
...
Response.Redirect("BaseAndRepeats.aspx?id=" + r.Event.ID);
In the template class I have I have
LinkButton lb;
public MyTemplate(..., LinkButton _lb)
{
...
lb = _lb;
...
public void InstantiateIn(System.Web.UI.Control container)
{
...
...
// various conditional statements
lb.CommandArgument = mylist[rowCount].ReqtID.ToString() + ";" + mylist[rowCount].RotaUser;
container.Controls.Add(lb);
...
The break point in the handler is never reached
I thought I was creating the linkbutton in the right place
the linkbutton appears in the grid quite happily
when I click on the linkbutton there is a call
to Page_PreInit and to Page_Load and as I expected
it is a postback.
But AssignAll_Click is never called.
In the browser footer it shows "javascript: __dooPsotabck(..." when you hover
over the buttonlink
I believe the problem is this line:
lb.Command += new CommandEventHandler(AssignAll_Click);
Change it to:
lb.Command += AssignAll_Click;
Edit:
Also you want to move it from Page_PreInit to Page_Init but you may find more success with it in Page_Load (outside the IsPostBack). Here's an example that works for me:
On the ASPX page:
<asp:Panel ID="TestPanel" runat="server" />
Codebehind:
protected void Page_Init(object sender, EventArgs e)
{
//Init used because TestPanel doesn't exist yet
CreateTestButton();
}
private void CreateTestButton()
{
var lb = new LinkButton();
lb.Text = "hello";
lb.Command += lb_Command;
TestPanel.Controls.Add(lb);
}
void lb_Command(object sender, CommandEventArgs e)
{
throw new NotImplementedException();
}
Going over your code it looks like your adding another column into your GridView and creating a button inside that column for each row - but you've got the column being added on Page_Load and the button being created and bound to it before in Page_PreInit
Related
I am adding dynamic LinkButton in Data Gridview, which will take me to a new page in C# asp.net. In starting, I am select value from Dropdown control. It will reload the page and display data in Gridview. In Gridview every row has dyanmic Linkbutton. When I click on Linkbutton in gridview, it is not working and page was reloaded and it hide the linkbutton.
My code is working when dropdown code pasted on page_load method.
I have researching since last 7 hours, view most of the answers but nothing is working on my problem.
As per my research, I found that after page reload LinkButton lost is state(I am not sure.).
Thanks in Advance...
using System;
using System.Web.UI.WebControls;
namespace aweFinalTTA.TTA.BatchReport
{
public partial class CenterBatchList : System.Web.UI.Page
{
protected aweFunctionNew aweApi = new aweFunctionNew();
protected aweCodePublic aweCode = new aweCodePublic();
protected LinkButton linkButton01;
protected GridView gdv;
protected DropDownList ddlTTCCode;
override protected void OnInit(EventArgs e)
{
aweApi.showForm(aweApi.getManageFieldDT("select * from manage_field where table_name='TTCBatchList'"), frmBatchList);
ddlTTCCode = (DropDownList)frmBatchList.FindControl(frmBatchList.ID + "ddlTTCCode");
ddlTTCCode.SelectedIndexChanged += new EventHandler(ddlTTCCode_SelectedIndexChanged);
frmBatchList.Controls.Add(aweApi.addGridViewNew("EmpGrid", "List of Batch Created"));
gdv = (GridView)frmBatchList.FindControl("EmpGrid");
gdv.RowDataBound += OnRowLinkBound;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
aweApi.getDDL(ddlTTCCode, "select TTCCode,TTCCode from TTCDetail where TTARNO='" + Session["TTARNO_01"].ToString() + "' and TTCDetail.TTCCode in (Select TTCCode from TTCCourseListOfTTC) and TTCDetail.TTCCode in (Select TTCCode from TTCInfraDetail) and TTCDetail.TTCCode in (Select TTCCode from TTCFacility) order by LastUpdatedDate desc", true);
TemplateField tfieldCheckbox = new TemplateField();
tfieldCheckbox.HeaderText = "Select";
gdv.Columns.Add(tfieldCheckbox);
}
}
protected void ddlTTCCode_SelectedIndexChanged(object sender, EventArgs e)
{
gdv.DataSource = aweApi.getResultsDT("select * from BatchMain where TTCCode='TTC0000002008'");
gdv.DataBind();
gdv.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void OnRowLinkBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton linkButton = new LinkButton();
linkButton.ID = "link";
linkButton.Text = "Edit";
linkButton.ForeColor = System.Drawing.Color.Blue;
linkButton.Click += linkButton_Click;
e.Row.Cells[0].Controls.Add(linkButton);
}
}
protected void linkButton_Click(object sender, EventArgs e)
{
// GridViewRow gr = ((sender as LinkButton).NamingContainer as GridViewRow);
/// Session["TTCBatchId_01"] = gr.Cells[2].Text.Trim(); /*For first cell value of Row */
Response.Write("linkbutton_click is working");
aweCode.showMessage(this, "aaaaaa");
//Response.Redirect("~/TTA/BatchReport/BatchAddCandidate");
}
}
}
My problem is that I dynamically create a table where each cell includes a linkbutton, that when clicked is supposed to remove that cell from the table.
(It is i bit more complex than that but I will not go into those details, just saying that a workaround will not do) I have read a few post on this and it usually is mentioned that the control has too be (re)made in page load or before. I have tried to run the method that runs setCellContent from both page load and page init and pre init but the _lnkBntRemoveSlotFromTable_Click method
is never called as the linkbuttons are clicked. And I am beginning to wonder there is something else wrong than just when the controls are created/recreated.
For each cell the table consist of, this is what is done:
private TableCell setCellContent(string day, DateTime timeOfDay){
TableCell newCell = new TableCell();
LinkButton lb = new LinkButton();
lb.ID = (++global_counter_id).ToString();
lb.Text = timeOfDay.ToShortTimeString();
lb.CommandArgument = timeOfDay.ToString();
lb.Command += new CommandEventHandler(_lnkBntRemoveSlotFromTable_Click);
newCell.Controls.Add(lb);
return newCell;
}
The method I want to be called:
public void _lnkBntRemoveSlotFromTable_Click(object sender, CommandEventArgs e)
{
//1. Make changes to the table
}
But the method is never called.
Finally got it working. A few changes made it work. It had ofcourse to do with when the table was created and how the id was created. For advice for others here is an example of when it works.. And make sure the ID of the dynamic control stays the same across page loads.
public partial class _default : System.Web.UI.Page
{
static int i = 0;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
LinkButton lb = new LinkButton();
lb.ID = "id";
lb.Text = "Click me";
lb.CommandArgument = "argument";
lb.Command += new CommandEventHandler(method_to_call);
this.Panel.Controls.Add(lb);
}
private void method_to_call(object sender, CommandEventArgs e)
{
i++;
this.Label.Text = i.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
Trying to add buttons programmatically to a webform.
Some work - others don't.
In the code below I add btnY and btnX in the Page_Load.
These both work - they show on the page and fire the event
and the code in the event handler works....
In the page load I also run bindData which gets a DataTable
and uses the data to create controls.
in the example I am only creating Button.
These buttons will appear on the page correctly but when clicked
they only do a postback ..
the code in the event handler doesn't work - does it get called?
The event handler is the same for all the buttons.
Any ideas why or how I can make it work?
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(btn("btnY", "Y"));
Pages P = new Pages();
bindData(P.DT);
PlaceHolder1.Controls.Add(btn("btnX", "X"));
}
Button btn(string id, string text)
{
Button btn1 = new Button();
btn1.ID = id;
btn1.Text = text;
btn1.Click += new System.EventHandler(this.btn_click);
return btn1;
}
protected void bindData(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
render(Convert.ToInt32(row["PageKey"]));
}
}
protected void render(int pageKey)
{
PlaceHolder1.Controls.Add(btn("btn_" + pageKey.ToString(), "Edit"));
}
protected void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.ID;
Pages P = new Pages();
bindData(P.DT);
lt.Text = "ID=" + id;
}
Never mind .. figured it out .. example above should work, my actual code had a if (!Page.PostBack) that caused the problem
I am stuck on something: I am creating a hyperlink at runtime that has a navigation URL. I need to define its click event so that I can save a few values to the database. I did something like below but without success.
Could you please suggest an alternative?
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) {
if (e.Item is GridDataItem) {
HyperLink link = (HyperLink)gridDataItem["ContentTitle"].Controls[0];
link.ForeColor = System.Drawing.Color.Navy;
link.ToolTip = Common.grdTextCell(gridDataItem["ContentSummaryDescr"].Text);
link.NavigateUrl = "~/SomePath/" + gridDataItem["ContentName"].Text;
link.Target = "_blank";
link.Attributes.Add("onclick", "document.getElementById('" +
dummyBtn.ClientID + "').click();");
}
}
protected void dummyBtn_Click(object sender, EventArgs e) {
}
But the button click event is not firing, it simply navigates to the URL. What to do please?
For a server side event to fire you would need a LinkButton and not a HyperLink
LinkButton has a Click event handler which you can use.
HyperLink only redirects and has no corresponding Click event handler associated for server side code
You want a LinkButton, not a HyperLink.
Here's some sample code to get you started (not tested)
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
LinkButton link = (LinkButton)gridDataItem["ContentTitle"].Controls[0];
link.Click += dummyBtn_Click;
}
}
protected void dummyBtn_Click(object sender, EventArgs e)
{
Response.Write("dummyBtn_Click");
}
You should be using Link Button. Just replace your Hyperlink with LinkButton in your code.It should work.
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) {
if (e.Item is GridDataItem) {
LinkButton link = (LinkButton )gridDataItem["ContentTitle"].Controls[0];
link.ForeColor = System.Drawing.Color.Navy;
link.ToolTip = Common.grdTextCell(gridDataItem["ContentSummaryDescr"].Text);
link.NavigateUrl = "~/SomePath/" + gridDataItem["ContentName"].Text;
link.Target = "_blank";
link.Click += dummyBtn_Click;
}
}
protected void dummyBtn_Click(object sender, EventArgs e) {
}
I’m trying to dynamically declare an ImageButton.
I declare it and assign an ID and Image to it as follows:
ImageButton btn = new ImageButton();
btn.ImageUrl = "img/Delete.png";
btn.ID = oa1[i] + "_" + i;
btn.OnClick = "someMethod";
But when I try to assign an OnClick handler for the button it throws the following exception:
System.Web.UI.WebControls.ImageButton.OnClick is inaccessible due to protection level
You couldn't assign a value to a method like that, even if it were accessible. You need to subscribe to the event:
btn.Click += ClickHandlingMethod;
Take a look at this answer, it is related with dynamic controls and events
As Jon commented you cannot add a string to the event, in this case you need to add a handler for the event:
protected void Page_Init(object sender, EventArgs e)
{
var i = new ImageButton();
i.Click += new ImageClickEventHandler(i_Click);
this.myPanel.Controls.Add(i);
}
void i_Click(object sender, ImageClickEventArgs e)
{
// do something
}
Alternativeley
protected void Page_Init(object sender, EventArgs e)
{
var i = new ImageButton();
i.Click += (source, args) =>
{
// do something
};
this.myPanel.Controls.Add(i);
}
An example:
private void CreateAButton()
{
var button = new ImageButton();
button.ImageUrl = "yourimage.png";
button.ID = "Button1";
button.Click += ButtonClick;
Page.Form.Controls.Add(button);
}
private void ButtonClick(object sender, ImageClickEventArgs e)
{
// Do stuff here
// ...
}
You can use this code (one significant change) :
private void CreateAButton()
{
var button = new ImageButton();
button.ImageUrl = "yourimage.png";
button.ID = "Button1";
button.PostBackUrl = "http://www.towi.lt";
Page.Form.Controls.Add(button);
}
Trick is in "PostBackUrl". If you write correct link it will redirects to it (as in example). In other cases this will add original server name, '/' and text you entered. For example 'xxx' will be turned to "http://yourservername/xxx". It is very useful, when you working with redirects to same ISS, but different sites and dynamically creating buttons for users.