How can I call eventhandler? - asp.net

void lbl_Click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
int currentPage = int.Parse(lnk.Text);
int take = currentPage * 10;
int skip = currentPage == 1 ? 0 : take - 10;
FetchData(take, skip);
}
Hi,
I want to call the method lbl_Click() whenever the click happens.
How can I define any aspx tag to call a function " lbl_Click()" whenever the click happens? or can I use javascript to invoke this "lbl_Click()" function?

Code for Event handler lbl_Click would be executed only when Click Event is fired from the link button. Functionally, this should happen when you click your paging link buttons.
Try to put a breakpoint in lbl_Click function and fire event by clicking on the paging link buttons in UI.
Since, it is still not working for you. I have created a small working page to show you how it should be.
Code Behind
using System;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
CreateDynamicLinkControls();
}
private void CreateDynamicLinkControls()
{
for (int i = 0; i < 10; i++)
{
LinkButton lk = new LinkButton();
lk.Click += new EventHandler(lbl_Click);
lk.ID = "lnkPage" + (i + 1).ToString();
lk.Text = (i + 1).ToString() + " ";
this.form1.Controls.Add(lk);
}
}
void lbl_Click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
int currentPage = int.Parse(lnk.Text.Substring(0, 1));
lblLinkText.Text = currentPage.ToString();
}
}
ASPX Page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
You Clicked : <asp:Label runat="server" ID="lblLinkText"></asp:Label>
</div>
</form>
</body>
</html>
Using this Code
Try to run the page and then link button would appear on the page, label is placed on the page which displays which page was clicked.

Related

Creating dynamic button and its event handler

I am trying to use dynamics buttons and events. When I clicked static button and I showed dynamic button. But When I clicked dynamic button I didn't work dinamikButon_Click event. What is my wrong? Sorry my language. Thx in advance.
Default.aspx.cs is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWebApplication
{
public partial class _Default : Page
{
int i = 1;
Button dinamikButon;
protected void Page_Load( object sender, EventArgs e )
{
}
protected void btnStatik_Click( object sender, EventArgs e )
{
dinamikButon = new Button
{
Text = "Dinamik" + i,
ID = "btnDinamik" + i,
CommandArgument = "commandArgument",
CommandName = "commandName"
};
dinamikButon.Click += dinamikButon_Click;
panel1.Controls.Add( dinamikButon );
i++;
}
void dinamikButon_Click( object sender, EventArgs e )
{
Label1.Text = "Merhaba dinamik butondan geliyorum.";
}
}
}
that's because when the page posts back the button doesn't exist. You have to create the buttons on page Load or PreInit. Microsoft suggests PreInit You can dynamically set a master page or a theme for the requested page, and create dynamic controls.
int i = 1;
Button dinamikButon;
private void Page_PreInit(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
CreateButton();
}
}
protected void btnStatik_Click( object sender, EventArgs e )
{
CreateButton();
}
private void CreateButton()
{
dinamikButon = new Button
{
Text = "Dinamik" + i,
ID = "btnDinamik" + i,
CommandArgument = "commandArgument",
CommandName = "commandName"
};
dinamikButon.Click += dinamikButon_Click;
panel1.Controls.Add( dinamikButon );
i++;
}
Update:
Do do what you've asked now we have to specify that the button has been created using either viewstate, querystring or session.
In this example I'll use a session:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Page.IsPostBack)
{
if (Session["Created"] != null)
{
CreateButton();
}
}
}
private void CreateButton()
{
dinamikButon = new Button
{
Text = "Dinamik" + i,
ID = "btnDinamik" + i,
CommandArgument = "commandArgument",
CommandName = "commandName"
};
Panel1.Controls.Add(dinamikButon);
dinamikButon.Click += dinamikButon_Click;
i++;
Session["Created"] = "true";
}
private void dinamikButon_Click(object sender, EventArgs e)
{
//your action here
}
To fill value in "Label1" control using dynamic button
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DynamicCtrl._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function dynamicevnt() {
document.getElementById("Label1").innerHTML = "Merhaba dinamik butondan geliyorum.";
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnStatik" runat="server" Text="Click" OnClick="btnStatik_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Panel ID="panel1" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicCtrl
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStatik_Click(object sender, EventArgs e)
{
CreateButton();
}
private void CreateButton()
{
int i = 1;
Button dinamikButon = new Button();
dinamikButon.Text = "Dinamik" + i;
dinamikButon.ID = "btnDinamik" + i;
dinamikButon.OnClientClick = "return dynamicevnt();";
dinamikButon.Click += new EventHandler(dinamikButon_Click);
panel1.Controls.Add(dinamikButon);
i++;
}
protected void dinamikButon_Click(object sender, EventArgs e)
{
Label1.Text = "Merhaba dinamik butondan geliyorum.";
}
}
}

How do I have a usercontrol add a Html String to Head of a MasterPage

I know this is easy when you know what you are adding. For example, with a UI control its
Page.Header.Controls.Add([control])
However, I am pulling HTML code from a CMS database. In other words, I need to add a string to the Head section of the master page.
You can add a Literal control to the Header by using code similar to the one you show in your question:
public partial class MyUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
var lit = new LiteralControl();
lit.Text = "<link href=\"test.css\" rel=\"stylesheet\" />";
Page.Header.Controls.Add(lit);
}
}
If you're using a master page, you could:
Master page markup:
<html>
<head runat="server">
<asp:ContentPlaceHolder ID="MyHeadContentPlaceHolder" runat="server"></asp:ContentPlaceHolder>
</head>
</html>
Content page markup:
<asp:Content ID="MyContent" ContentPlaceHolderID="MyHeadContentPlaceHolder" runat="server">
<asp:Literal ID="MyLiteralForCmsContent" runat="server"></asp:Literal>
</asp:Content>
Content page code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Load the literal with content from the CMS.
this.MyLiteralForCmsContent.Text = ""; //Hook up the call to the CMS here.
}
}

Why does GridView not render the header row as thead after postback?

Setting TableSection = TableRowSection.TableHeader after the grid is bound works initially, putting the header row in thead. After a postback (where the grid is not re-bound) the header row reverts to the table body. I expect the header row to stay in thead; can someone explain why this is not the case or what I am doing wrong?
Sample:
Click the button to cause a postback. The header is not orange after the postback since it's not in thead anymore.
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="gridtest.aspx.cs" Inherits="ffff.gridtest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
thead th { background-color:Orange;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div><asp:Button ID="Button1" runat="server" Text="Button" />
this button is here just to trigger a postback</div>
<asp:GridView ID="gv1" runat="server"></asp:GridView>
</form>
</body>
</html>
code
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ffff
{
public partial class gridtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gv1.DataBound += new EventHandler(gv1_DataBound);
if (!IsPostBack) { BindGrid(); }
}
void Page_PreRender(object sender, EventArgs e)
{
if (gv1.HeaderRow != null)
System.Diagnostics.Debug.WriteLine(gv1.HeaderRow.TableSection); // still TableHeader after postback
}
void gv1_DataBound(object sender, EventArgs e)
{
if (gv1.HeaderRow != null)
{
gv1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
private void BindGrid()
{
gv1.DataSource = this.Page.Controls;
gv1.DataBind();
}
}
}
Use the Pre_Render_Complete event instead to add the table section. This will ensure the thead section is always added. As you are currently doing it on DataBound the section will only be added when the data is bound.
protected override void OnPreRenderComplete(EventArgs e)
{
if (gv1.Rows.Count > 0)
{
gv1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
Feel free to change the row check I use to checking the Header Row exists as you currently do.
You must set TableSection after DataBind method.
gv1.DataSource = this.Page.Controls;
gv1.DataBind();
gv1.HeaderRow.TableSection = TableRowSection.TableHeader;
Just put the below code in prerender event of gridview
protected void gv_PreRender(object sender, EventArgs e)
{
if (gv.Rows.Count > 0)
{
gv.UseAccessibleHeader = true;
gv.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}

Can't get 'Text' property with asp-control

How do I get properties (e.g. Text) with asp.net controls that were created programatically when page loading when IsPostBack parameter is true?
Schema:
creating control (e.g. TextBox box = new TextBox(); box.ID = "BoxID")
display control in page (e.g. SomeControlInPageID.Controls.Add(box))
user see this textbox (with id "BoxID", but we don't have a possibility to get text property use BoxID.Text, because it control was created programatically!) in page & puts in it some text
user click in button (asp:Button) in page and start page reloading process
start Page_Load method & IsPostBack parameter takes the true value
i try to use this code to get Text property in Page_Load method, but it's not work...:
void Page_Load()
{
if (Page.IsPostBack)
{
TextBox box = SomeControlInPageID.FindControl("BoxID") as TextBox;
string result = box.Text;
}
else
{
// creating controls programatically and display them in page
...
}
}
box.Text in this code always takes null value.
The key here is you need to make sure you recreate the dynamic controls each time the page is loaded. Once the controls are created, ASP.NET will be able to fill the posted back values into those controls. I've included a full working example below. Notice I add the control in the OnInit event (which will fire before Page_Load), and then I can read the value back out in the Page_Load event if a postback has occurred.
<%# Page Language="C#" AutoEventWireup="true" %>
<html>
<body>
<form id="form1" runat="server">
<asp:Panel ID="myPanel" runat="server" />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
<br />
Text is: <asp:Literal ID="litText" runat="server" />
</form>
</body>
</html>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
if(Page.IsPostBack)
{
var myTextbox = myPanel.FindControl("myTextbox") as TextBox;
litText.Text = myTextbox == null ? "(null)" : myTextbox.Text;
}
}
protected override void OnInit(EventArgs e)
{
AddDynamicControl();
base.OnInit(e);
}
private void AddDynamicControl()
{
var myTextbox = new TextBox();
myTextbox.ID = "myTextbox";
myPanel.Controls.Add(myTextbox);
}
</script>
Please have a look into pageLifeCycle of an aspx page. You'll have to add the textbox within the Page_Init handler. Afterwards you may access your textBox in page_load event.
protected void Page_Init(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.ID = "textbox1";
tb.AutoPostBack = true;
form1.Controls.Add(tb);
}
protected void Page_Load(object sender, EventArgs e)
{
/// in case there are no other elements on your page
TextBox tb = (TextBox)form1.Controls[1];
/// or you iterate through all Controls and search for a textbox with the ID 'textbox1'
if (Page.IsPostBack)
{
Debug.WriteLine(tb.Text); /// only for test purpose (System.Diagnostics needed)
}
}
hth

FindControl for nested controls in UserControl returns null

I have a very weird issue. I have a UserControl that has some controls inside. I want to refer those controls after, in another postback. But when I try to get them the Controls property of my controls returns null.
I'm working on vs2008.
Here is the sample code:
public partial class MyUserControl : System.Web.UI.UserControl, INamingContainer
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.Controls)
{
Response.Write(control.ClientID);
}
}
private void MyTable()
{
Table table = new Table();
TableRow row = new TableRow();
TableCell cell = new TableCell();
CheckBox check = new CheckBox();
check.ID = "theId";
check.Text = "My Check";
check.AutoPostBack = true;
cell.Controls.Add(check);
row.Cells.Add(cell);
check = new CheckBox();
check.ID = "theOther";
check.AutoPostBack = true;
check.Text = "My Other Check";
cell = new TableCell();
cell.Controls.Add(check);
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
}
protected override void Render(HtmlTextWriter writer)
{
MyTable();
base.Render(writer);
}
}
and the Default.aspx page is something like:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.cs" Inherits="Tester.Default" %>
<%# Register TagPrefix="uc1" TagName="MyControl" Src="~/MyUserControl.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Unbenannte Seite</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:MyControl ID="MyControlInstance" runat="server" />
</div>
</form>
</body>
</html>
I don't know if I'm lost in some part of the ASP.NET life cycle. But this situation is making me crazy. Any help would be very grateful.
Create your child controls (MyTable) in either CreateChildControls or OnInit:
protected override void CreateChildControls()
{
MyTable();
base.CreateChildControls();
}
Or
protected override void OnInit(object sender, EventArgs e)
{
MyTable();
base.OnInit(e);
}
You shouldn't/cannot create controls in Render as it occurs after Page_Load. See the ASP.Net Page Lifecycle here.
I believe it is because the Render event occurs after Page_Load, so when you are trying to iterate your control collection, it hasn't been set up yet. Most common solution is to override CreateChildControls to get the proper timing down.

Resources