Making a Control to be runat=server - c#

In my application I have created a button dynamically & its name is "Dynamic_Button". Is it possible to make the button to be runat=server. I just tried the code but it doesn't work.
Dynamic_Button.Attributes.Add("runat","server");
Is there anyother ways to make it in serverside ?

When you manually instantiate a server control, there's no need to add the runat="server" attribute. This is a special attribute that's used only by the ASP.NET page parser to distinguish server controls from other markup.
The OnClick attribute in markup corresponds to the Click server-side event, which you hook up using the += operator.
So:
LinkButton lb = new LinkButton();
lb.ID = "LinkButton1";
lb.Click += click_event;
lb.Text = "testtext";
And the event handler
protected void click_event(object sender, EventArgs e)
{
}
In this example there is no need to add runat server because it already has it.
Have a look at this answer: https://stackoverflow.com/a/11337397/284240

This and this will guide you in creating and adding buttons at run time as well assigning events(client and server side).

Related

EnableViewState for html tag

I am quite new and I will like to ask a question. Please see the html and codebehind.
HTML
<ul id="menu" runat="server" EnableViewState="True"></ul>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var liItem = new HtmlGenericControl("li");
var aItem = new HtmlGenericControl("a");
liItem.Attributes.Add("class", "test");
aItem.Attributes.Add("href", "#");
aItem.InnerText = "please work";
liItem.Controls.Add(aItem);
menu.Controls.Add(liItem);
}
}
Once postback, the UL data is lost though I have enabled the viewstate. I remember it works last time but now it is not. Anybody can advise? Thanks a lot
This happens because you are dynamically adding data via your first load (!IsPostback), and thereafter (when Page_Load runs again) the data is being lost. You have to keep in mind that EnableViewState is a ASP.NET specific property, So it will only work on server controls inheriting from System.Web.UI.Control
The only way you can achieve this is by either creating your html tags on each and every page load (i.e remove your !IsPostBack check)
or adding a ASP.NET control to the page which supports ViewState (Gridview, ListView, Label, Button etc).

ASP.NET use Hyperlinks instead of Buttons

I would like to add a Logout link to my form so our employees can log out of the job they are working on.
The code behind in my application is simple:
protected void Logout_Click(object sender, EventArgs e) {
MasterPage.Logout();
}
A asp.Button I can code by wiring up the onClick event.
How would I call this method using a asp.Hyperlink control?
You're looking for the LinkButton control. That gets rendered as an a tag, and the page will be posted back to itself so that your OnClick function can be invoked.
The Hyperlink control renders a simple hyperlink, which won't allow you to wire it up to a click handler. Try the LinkButton control instead.
Replace Hyperlink with LinkButton.
Hyperlink has no server side events.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.aspx
One thing I might suggest is to simply use CSS to style your actual-fact button to adopt the look of a link, as opposed to imitating a button from something that will likely be styled differently anyway.
When imitating a button, you are relying on the user having script enabled in their browser:
The LinkButton control renders JavaScript to the client browser. The
client browser must have JavaScript enabled for this control to
function properly.
Whereas a button that is a button will submit the form.
EDIT:
As per your comment, here is a quick example you could easily adapt:
CSS:
.hyperLinkButton
{
border:none;
background:none;
color:Navy;
cursor:pointer;
}
.hyperLinkButton:hover
{
text-decoration:underline;
}
Mark-up:
<asp:Button runat="server" CssClass="hyperLinkButton"
Text="Is it a HyperLink? Is it a LinkButton? No, it's a Button!" />

ASP.Net ImageButton not firing onclick

I'm testing out two ImageButton controls one is set programmatically inside a GridView_RowDataBound function and the other is hard-coded on the client side as follows:
Static ImageButton (Works and fires ImageButton_Click):
<asp:ImageButton OnClick="ImageButton_Click" runat="server" ID="Foo" ImageUrl="images/edit-icon.png" />
Dynamic ImageButton (Does not work, won't fire ImageButton_Click):
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
.
.
.
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.Click += new ImageClickEventHandler(ImageButton_Click);
e.Row.Cells[5].Controls.Add(i);
.
.
.
}
The Dynamic ImageButton renders as follows
<input type="image" name="GridView1$ctl24$DGV1$ctl02$icon_1234" id="GridView1_ctl24_DGV1_ctl02icon_1234" title="Click to add a new comment" src="/images/edit-icon.png" onclick="ImageButton_Click;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("GridView1$ctl24$DGV1$ctl02$icon_1234", "", true, "", "", false, false))" style="border-width:0px;">
I notice the dynamic image button contains "onclick" vs the static imagebutton which has "OnClick", not sure if that makes a difference. I've been stumped on this for the last few hours, I don't know why the dynamic ImageButton is not firing. Please help.
UPDATE:
Thanks for all the feedback, I only need to process the ID of the ImageButton and it doesn't have to be server-side. Is there anyway I can do this from client-side using JavaScript in order to avoid postback? I tried re configuring the ImageButton as follows:
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.OnClientClick = "submitComment(i.ID);return false;";
e.Row.Cells[5].Controls.Add(i);
I specify this function in the header of my web form
<head runat="server">
<script type="text/javascript">
submitComment(i.ID){
//Call WebMethod and pass comment along with this button's testID
}
</script>
</head>
But I get the following error when I click on the edit-icon ImageBtn:
Uncaught Reference Error: icon_12345 is not defined.
How is this so? If the edit-icons are already rendered and I'm just using client-side Javascript, shouldn't they already be defined and able to be properly referenced? This seems very counter intuitive to me. Am I missing something here? Is there some other control, besides and ImageButton, I can use for rendering the image without worrying about a postback, but that can still call the Javascript and pass along it's ID? What about using a regular Image control and just wiring it's onclick property to call the the submitComment function.
The problem is that on postback ASP.NET does not remember that you dynamically added a control on the previous request. The control simply does not exist in the control tree so the event will not fire.
You are asking for pain and suffering when trying to dynamically add controls. The control must be recreated by you before Page_Load if you want the event to fire. See http://forums.asp.net/t/1186195.aspx/1 for more details.
I would just hide the ImageButton for rows that don't need it.
You have to DataBind on each postback to get the control back into the ControlTree.
Maybe you could try something like this? Just make a regular img element with a data binding expression for the onclick attribute. "ID" must be a field in the gridview datasource.
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img src="/images/edit-icon.png" onclick="submitComment('<%# Eval("ID", "icon_{0}") %>');"></img>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Untested, but I've used something like this before. ASP.NET can get picky parsing the databinding expression.
If your page is routed, just add this code to masterpage on_load or on the page where you have the form
form1.Action = Request.Url.PathAndQuery;

How to add a Onclick function to a Dynamic LinkButton?

I need to add a Onclick attribute to my LinkButton which I am dynamically generating. How to add it?
Here is the code I came so far and struck with:
foreach(string i in List)//list has more than 50 data's
{
LinkButton link = new LinkButton();
link.Text = topics;
link.ID = topics;
link.Attributes.Add("runat", "server");
link.Click += new EventHandler(this.lnk_Click);
div_ID.Controls.Add(link);
div_ID.Controls.Add(new LiteralControl("<br />"));
}
public void lnk_Click(object sender,EventArgs e)
{
string ctrlId = ((Control)sender).ID;
GMethod(ctrlId); //handles some function in which i pass the id of the particular lnk button
}
I could call this lnk_Click from my LinkButton on dynamic generation. Its onclick attribute is not getting added to the link button. Please help me out on this guys. I am on urge.
You don't need to add the runat="server" attribute, as that will be done automatically. You've assigned the OnClick event handler, so you should be all set there too.
Since you're creating these controls dynamically, make sure that you have code in place to regenerate the LinkButton controls after postback, otherwise your event handler won't fire. Also make sure to assign the same IDs when regenerating it after postback.
I was also facing the same issue that the onClick event of the dynamically created hyperlink was not getting fired. I was making the mistake of placing the code of dynamic creation of hyperlink within "if(!IsPostBack)" and was assigning a random id to the hyperlink every time. So, please try assigning a unique ID and keep the code outside "if(!IsPostBack)". Will work.

Attach RequiredValidator on custom server control rendering a TextBox

I don't know whether this is really possible, but I'm trying my best.
If I have a (complex) custom server control which (beside other controls) renders a TextBox on the UI. When placing the server control on a page, would it be possible to attach a RequiredField validator to that server control, such that the validator validates the Text property of that control which points to the Text property of the rendered TextBox?
Of course I could incorporate the RequiredField validator directly into the server control, but this is for other reasons not possible (we are rendering RequiredField validators automatically on the UI).
Thanks for your help.
I think one solution is to put your TextBox control inside a Panel then you add the RequiredValidator control dynamically on the Page_Load event handler.
<asp:Panel ID="Panel1" runat="server">
<MyCustomTextBox ID="TextBox1" runat="server"></MyCustomTextBox>
</asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Button" />
then
protected void Page_Load(object sender, EventArgs e)
{
var validator = new RequiredFieldValidator();
validator.ControlToValidate = "TextBox1";
validator.ErrorMessage = "This field is required!";
Panel1.Controls.Add(validator);
}
I put the CustomTextBox inside the panel to assure that the validation controle place is correct when added
I got it, the 2nd time that I'm answering to my own post :) Next time I'll do a deeper research before.
For those of you that may encounter the same problem. You have to specify the ValidationProperty attribute on your server control's class. For instance if your server control exposes a property "Text" which is displayed to the user and which should also be validated, you add the following:
[ValidationProperty("Text")]
Then it should work.

Categories