asp.net: Use javascript set lable value but it doesn't save - asp.net

This is my code:
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<input type="button" onclick="ontextchange();" />
<asp:Button ID="Button1" runat="server"
Text="Button" onclick="Button1_Click" />
</div>
function ontextchange() {
document.getElementById("Label1").innerText="New";
}
The problem is: I can change the lable value via javascript, but when I click the Button1, the lable value become the first one "Label". How can I get the new value when I click the asp.net button?

You may try to use a hidden field instead, but you need to keep them synchronized in your client-side script and your server-side event handler.
<asp:Hidden ID="Hidden1" runat="server" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
In JavaScript:
function ontextchange() {
// Set the label for the visual result
document.getElementById("Label1").innerText="New";
// Set the hidden input for the server
document.getElementById("Hidden1").value="New";
}
Server-side you can read the hidden input and update the label (again, keeping them synchronized):
protected void Button1_Click(object sender, EventArgs e)
{
// Set the label text to the value from the hidden input
string value = Hidden1.Value;
Label1.Text = value;
}

Related

Can a button validate more validation groups?

I have 3 types of validators:
It is part of "VG1" validation group
It is part of "VG2" validation group
It is not part of any validation groups
I have two buttons, B1 and B2.
I would like to validate B1.Click if and only if all validators of the first and third type successfully validated the controls associated to them.
I would like to validate B2.Click if and only if all validators of the second and third type successfully validated the controls associated to them.
Is this possible in ASP.NET? If so, can you tell me how can I do this or where could I read something which would enlighten me in this question?
EDIT:
function isValidButton1()
{
var VG1 = Page_ClientValidate("VG1");
var empty = Page_ClientValidate("");
return VG1 && empty;
}
This works well, however, if VG1 is invalid, then the messages will disappear, because of the validation of the empty group. Is there a solution to show all validation error messages? Thank you.
EDIT2:
function isValidSaveAsClosed()
{
Page_ClientValidate("");
Page_ClientValidate("VG1");
var groups = [];
groups[0] = undefined;
groups[1] = "VG1";
var valid = true;
for (var f in Page_Validators)
{
if (jQuery.inArray(Page_Validators[f].validationGroup, groups) >= 0)
{
ValidatorValidate(Page_Validators[f]);
valid = valid && Page_Validators[f].isvalid;
}
}
return valid;
}
The function above solves my problem.
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return Validate()" />
<script type="text/javascript">
function Validate()
{
var isValid = false;
isValid = Page_ClientValidate('VG1');
if (isValid)
{
isValid = Page_ClientValidate('VG2');
}
return isValid;
}
</script>
try this....hope it will help
Yes a button can validate more then one validation groups.
Inside the button_click you can validate the groups as
Page.Validate("VG1");
Page.Validate("VG2");
if (Page.IsValid)
{
// Page is valid so proceed..!!
}
I am adding another answer since adding to my last existing answer would make the answer too big for anyone to read.
In this answer, I have expanded on my last answer so multiple validation groups are automatically hooked up both on client-side as well as server-side. This means you do not need to call Page_ClientValidate("group1,group2") in JavaScript onclick event of button, since it will occur automatically. Also, the server-side validation for multiple groups will happen automatically.
The markup and code-behind for this is given below. You can try the aspx code that I have provided and test it in a website project. To test if automatic server-side validation occurs, you must set EnableClientScript="false" for each of the three validators.
Explanation of approach for automatic validation of multiple groups
If you want to implement multiple validation groups, the following steps need to done in your aspx page. Make sure that in your markup you mention a comma-delimited list of validation groups for ValidationGroup property of button control if you need to validate multiple groups at a time.
you need to override the JavaScriptmethod IsValidationGroupMatch by adding JavaScript to end of your aspx page (The code for this override is given at end of markup code below and you can copy/paste it into your aspx page); this is a standard method provided by ASP.Net validation framework.
you need to hookup the button with multiple validation groups for client-side validation since this is NOT done automatically by ASP.Net; for this, you have to call the method HookupValidationForMultipleValidationGroups in code-behind in Page_Load event for each button that has multiple validation groups.(you can copy/paste this method given in second-code snippet into the code-behind of your aspx page)
you need to override the server-side method Validate to add functionality for multiple validation groups since this is missing in ASP.Net.(you can copy/paste this method given in second-code snippet into the code-behind of your aspx page)
Markup of aspx with multiple validation groups for a button
<%# Page Language="C#" AutoEventWireup="true" CodeFile="MultipleValidationGroupsByOneButton.aspx.cs" Inherits="MultipleValidationGroupsByOneButton" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
TextBox1 :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 needs input" ControlToValidate="TextBox1" ForeColor="Red" ValidationGroup="group1"></asp:RequiredFieldValidator>
<br />
<br />
TextBox2 :
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="TextBox2 needs input" ControlToValidate="TextBox2" ForeColor="Red" ValidationGroup="group2"></asp:RequiredFieldValidator>
<br />
<br />
TextBox3 :
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="TextBox3 needs input" ControlToValidate="TextBox3" ForeColor="Red" ValidationGroup="group3"></asp:RequiredFieldValidator>
<br />
<br />
</div>
<asp:Button ID="btnMultipleValidationGroups" runat="server" Text="Validate group1 and group2" ValidationGroup="group1,group2" OnClick="btnMultipleValidationGroups_Click" />
<asp:Button ID="btnGroup1" runat="server" Text="Validate only group1" ValidationGroup="group1" OnClick="btnGroup1_Click" />
<asp:Button ID="btnGroup2" runat="server" Text="Validate only group2" ValidationGroup="group2" OnClick="btnGroup2_Click" />
<asp:Label ID="lblMessage" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
<script type="text/javascript">
window["IsValidationGroupMatch"] = function (control, validationGroup) {
if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
var isGroupContained = false;
if (typeof (control.validationGroup) == "string") {
controlGroup = control.validationGroup;
var controlGroupArray = [];
if (validationGroup.indexOf(",") > -1) {
controlGroupArray = validationGroup.split(",");// validationGroup.split(",");
}
for (var i = 0; i < controlGroupArray.length; i++) {
if (controlGroupArray[i].trim() == controlGroup.trim()) {
isGroupContained = true;
}
}
}
return (controlGroup == validationGroup || isGroupContained);
}
</script>
</form>
</body>
</html>
Code-behind of above aspx page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MultipleValidationGroupsByOneButton : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//always call this method in Page Load event for each button with multiple validation groups
HookupValidationForMultipleValidationGroups(btnMultipleValidationGroups);
}
//the method below will automatically hook up a button with multiple validation groups for client-side validation
private void HookupValidationForMultipleValidationGroups(IButtonControl button)
{
if (!Page.IsPostBack && button.ValidationGroup.Contains(","))
{
//hook up validation on client-side by emitting the appropriate javascript for onclick event of the button with multiple validation groups
PostBackOptions myPostBackOptions = new PostBackOptions((WebControl)button);
myPostBackOptions.ActionUrl = string.Empty;
myPostBackOptions.AutoPostBack = false;
myPostBackOptions.RequiresJavaScriptProtocol = true;
myPostBackOptions.PerformValidation = true;//THIS true value hooks up the client-side validation
myPostBackOptions.ClientSubmit = true;
myPostBackOptions.ValidationGroup = button.ValidationGroup;
// Add postback script so cleint-side validation is automatically hooked up for control with multiple validation groups
((WebControl)button).Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(myPostBackOptions));
}
}
//Override default Validate method so server-side validation of buttons with multiple validation groups occurs automatically
public override void Validate(string validationGroup)
{
if (validationGroup.Contains(","))
{
string[] validationGroups = validationGroup.Split(",".ToCharArray());
foreach (string group in validationGroups)
{
Page.Validate(group);
}
}
base.Validate(validationGroup);
}
protected void btnMultipleValidationGroups_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblMessage.Text = "Button with multiple validation groups was clicked";
}
}
protected void btnGroup1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblMessage.Text = "Button with Group1 validation group was clicked";
}
}
protected void btnGroup2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblMessage.Text = "Button with Group2 validation group was clicked";
}
}
}
A simpler approach that does not involve writting any aditional code is to simply replicate the validators wherever they are needed, as shown in the sample below:
<div>
<asp:TextBox ID="txt1" runat="server" placeholder="field1" />
<asp:RequiredFieldValidator runat="server" ID="req1a" ControlToValidate="txt1" ValidationGroup="group1" Display="Dynamic" />
<asp:RequiredFieldValidator runat="server" ID="req1b" ControlToValidate="txt1" Display="Dynamic" />
</div>
<div>
<asp:TextBox ID="txt2" runat="server" placeholder="field2" />
<asp:RequiredFieldValidator runat="server" ID="req2" ControlToValidate="txt2" />
</div>
<!-- Validate validators with empty ValidationGroup -->
<asp:Button runat="server" ID="btn1" Text="Validate All" />
<!-- Validate group1 validators -->
<asp:Button runat="server" ID="btb2" Text="Validate Group 1" ValidationGroup="group1"/>
First button will validate both textboxes, even though they are in diferent groups, while the second one will only validate the first textbox.
You can use Page_ClientValidate(validationgroup) function to validate a validation grouop.
like
function Validate(vgroup) {
return Page_ClientValidate(vgroup);
}
You can try
<asp:Button ID="B1" runat="server" Text="Button"
OnClientClick="return Validate('VG1') && Validate() " />
<asp:Button ID="B2" runat="server" Text="Button"
OnClientClick="return Validate('VG2') && Validate() " />
This is an old post but I had the same issue recently and the way I solved it is as explained below.
You can copy the code given in this post into your ASP.Net website project and test it for yourself. The first button i.e. the one on left is validating three validation groups at same time unlike the other two buttons.
Just include the JavaScript given at end of aspx page in code below, in which I have overridden the validation function IsValidationGroupMatch so multiple groups can be validated. Then, if you want to validate multiple groups on client-side, you must call the function Page_ClientValidate("group1,group2,group6,group5") to which you simply pass a comma-delimited list of validation groups.
(NOTE: But remember that by using this approach you can validate multiple validation groups on client-side only. This does NOT automatically also validate multiple groups on server-side. You must call the API function of Page_ClientValidate on client-side since multiple groups validation will not get automatically hooked up by ASP.Net framework.)
Sample aspx page code that allows validating multiple groups at same time on client-side
<%# Page Language="C#" AutoEventWireup="true" CodeFile="MultipleValidationGroupsByOneButton.aspx.cs" Inherits="MultipleValidationGroupsByOneButton" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
TextBox1 :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 needs input" ControlToValidate="TextBox1" ForeColor="Red" ValidationGroup="group1"></asp:RequiredFieldValidator>
<br />
<br />
TextBox2 :
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="TextBox2 needs input" ControlToValidate="TextBox2" ForeColor="Red" ValidationGroup="group2"></asp:RequiredFieldValidator>
<br />
<br />
TextBox3 :
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="TextBox3 needs input" ControlToValidate="TextBox3" ForeColor="Red" ValidationGroup="group3"></asp:RequiredFieldValidator>
<br />
<br />
</div>
<asp:Button ID="btnMultipleValidationGroups" runat="server" Text="Validate group1 and group2" onclientclick="if(!Page_ClientValidate('group1,group2,group3')) { return false;}" />
<asp:Button ID="btnGroup1" runat="server" Text="Validate only group1" ValidationGroup="group1" />
<asp:Button ID="btnGroup2" runat="server" Text="Validate only group2" ValidationGroup="group2" />
<script type="text/javascript">
window["IsValidationGroupMatch"] = function (control, validationGroup) {
if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
var isGroupContained = false;
if (typeof (control.validationGroup) == "string") {
controlGroup = control.validationGroup;
var controlGroupArray = [];
if (validationGroup.indexOf(",") > -1) {
controlGroupArray = validationGroup.split(",");
}
for (var i = 0; i < controlGroupArray.length; i++) {
if (controlGroupArray[i].trim() == controlGroup.trim()) {
isGroupContained = true;
}
}
}
return (controlGroup == validationGroup || isGroupContained);
}
</script>
</form>
</body>
</html>

modalpopupextender always shown and targetcontrolid is not working

I have a repeater and it has a column of linkbuttons in it. I want to add those linkbuttons to targetcontrolid but it failed because they are in the repeater. So i create an additional invisible button like this :
<asp:Button ID="btnFakePopUp" runat="server" Text="" visible="false"
onclick="btnFakePopUp_Click"/>
And in i tried to link the linkbutton to the invisible button in this code :
protected void lbtnPosition_Click(object sender, EventArgs e) {
btnFakePopUp_Click(sender, e);
}
protected void btnFakePopUp_Click(object sender, EventArgs e)
{
popupJob.Show();
}
And this is my modalpopupextender code (my prefix is asp: so dont get confuse) :
<asp:ModalPopupExtender ID="popupJob" runat="server" PopupControlID="panelPopup" CancelControlID="popupClose" TargetControlID="btnFakePopUp"
Drag="true" PopupDragHandleControlID="panelPopup">
</asp:ModalPopupExtender>
<asp:Panel ID="panelPopup" runat="server" BackColor="#ebf0ff" Width="300px">
<div>
test<br />
<asp:Button ID="btnSave" runat="server" Text="Save" />
<asp:Button ID="btnApply" runat="server" Text="Apply" />
<input id="popupClose" type="button" value="Close" />
</div>
</asp:Panel>
The problems are :
1. The panelpopup is always shown...(it should be hidden, and only be shown when the user click the link button)
2. Nothing happened when i tried to click the link button (the panelpopup should be shown)
Thank you :D
For a btnFakePopup invisible you could set the display:none with CSS
example:
<asp:ImageButton ID="btnFakePopUp" runat="server" style="display: none"></asp:ImageButton>
I don't understand why, but setting btnFakePopUp visibility to true corrected the problem. Now my modalpopupextender is running smoothly.

asp.net ajax like reorder list

I'm trying to create a draggable list to change the order some pictures are displayed in a product page. I wan't to be able to do this in the product edit page (same place where I add the pics and their description). So, when creating I have nothing inserted on the database and since the AJAX toolkit reorderlist only works with a datasource I was specifying the list as the source of the reorderlist and calling the databind method. In the item template of the reorder list I have a textbox to edit the pic description and a img that displays the photo. I can drag the items and the list gets reordered, however when I click save I can't get the updated text on the textbox and the order property on the picture doesn't get updated. I've tried manually getting the items in the reorderlist but they're always null even though the list shows 20 items the DataItem is empty. I've enabled viewstate and didn't help either.
Here's my code:
<ajaxToolkit:ReorderList ID="rdlPhotos" runat="server" SortOrderField="PhotoOrder" AllowReorder="true" PostBackOnReorder="true" ClientIDMode="AutoID" EnableViewState="true" ViewStateMode="Enabled">
<ItemTemplate>
<div>
<%--<eva:PhotoView ID="iPV" runat="server" Photo='<%# Container.DataItem %>' />--%>
<asp:Image ID="imgPhoto" runat="server" ImageUrl='<%# string.Format("http://eva-atelier.net/sparkle{0}", Eval("Path").ToString().Substring(1)) %>' Width="150" Height="150" />
<div class="formGrid">
<label class="formLabel">Title</label>
<asp:TextBox ID="txtTitle" runat="server" Text='<%#Bind("FileTitle") %>' />
<br />
<label class="formLabel">Description</label>
<asp:TextBox ID="txtDescription" runat="server" Text='<%#Bind("FileDescription") %>' />
<br />
</div>
<p>
<asp:Button ID="btnRemove" runat="server" Text="Remover" />
</p>
</div>
</ItemTemplate>
<ReorderTemplate>
<asp:Panel ID="pnlReorder" runat="server" />
</ReorderTemplate>
<DragHandleTemplate>
<div style="width:20px;height:20px;background-color:Red"></div>
</DragHandleTemplate>
</ajaxToolkit:ReorderList>
And below the C# code:
private void AddPhotosView()
{
if (_currentProduct.Photos != null && _currentProduct.Photos.Count > 0)
{
rdlPhotos.DataSource = _currentProduct.Photos;
rdlPhotos.DataBind();
}
}
I'm new to Asp.net I come from a large WPF background, sorry if I'm making basic question :)
Thanks
For updating order of ReorderList items add your handler for it's OnItemReorder event. In this case your handler may looks like this:
protected void ReorderHandler(object sender, ReorderListItemReorderEventArgs e)
{
var movedPhoto = _currentProduct.Photos[e.OldIndex];
_currentProduct.Photos.RemoveAt(e.OldIndex);
_currentProduct.Photos.Insert(e.NewIndex, movedPhoto);
_currentProduct.Photos.Save();
}
For updating FileTitle and FileDescription of single Photo it is easy to use OnUpdateCommand event of ReorderList and a button with attribute CommandName="Update" for each Photo.
And for updating all Photos at once just iterate through rdlPhotos.Items in next manner:
protected void SaveAllHandler(object sender, EventArgs e)
{
foreach (var riItem in rdlPhotos.Items)
{
var id = ((HiddenField)riItem.FindControl("itemID")).Value;
var title = ((TextBox)riItem.FindControl("txtTitle")).Text;
var description = ((TextBox)riItem.FindControl("txtDescription")).Text;
UpdatePhoto(id, title, description);
}
}
Remember that rdlPhotos.Items here are in initial order. And for identifying which Photo should be updated add hidden field with Photo.ID-value to ReorderList's ItemTemplate like this:
<asp:HiddenField runat="server" ID="itemID" Value='<%# Eval("ID") %>' />

How do I maintain user entered text in a TextBox nested in an UpdatePanel between updates?

I have an ASP.Net UpdatePanel that updates on a timer. Within the UpdatePanel and nested in a GridView, I have a TextBox that the user enters a value in with a submit button. Everything works fine, except if the user does not submit the value before the timed interval, the text is removed from the TextBox.
Is there a way to persist the user entry into the TextBox between updates? Is there a better way of doing this?
All suggestions welcome.
Respectfully,
Ray K. Ragan
Code Postscript:
aspx:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beginRequest);
function beginRequest() {
prm._scrollPosition = null;
}
</script>
<asp:Timer ID="Timer1" runat="server" Interval="900" OnTick="Timer1_Tick"></asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:DataList RepeatColumns="5" RepeatDirection="Horizontal" ID="dlMine" runat="server" OnItemCommand="Item_Command">
<ItemTemplate>
<div style="border:1px solid black;margin:3px;height:300px;text-align:center;padding:5px;">
<div style="width:150px;">
<asp:Label ID="lblTitle" runat="server" Text='<%# left(DataBinder.Eval(Container.DataItem,"title").ToString(), 75) %>'></asp:Label>
</div>
<asp:Label ID="Label1" runat="server" Text='<%# (DateTime)DataBinder.Eval(Container.DataItem,"end_date") %>'></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text='<%# String.Format("{0:C}",DataBinder.Eval(Container.DataItem,"current_value")) %>'></asp:Label>
<br />
<asp:TextBox ID="txtNewValue" runat="server"></asp:TextBox>
<asp:Button Visible='<%# (isInThePast((DateTime)DataBinder.Eval(Container.DataItem,"end_date"))) ? false : true %>' CssClass="bid_button" runat="server" CommandArgument='<%# Eval("ID") %>' CommandName="Revalue" ID="btnBid" Text="Submit New Valuation" />
</div>
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Tick += new EventHandler<EventArgs>(Timer1_Tick);
if (!IsPostBack)
{
dataBindList();
}
}
protected void dataBindList()
{
if (Request.QueryString["GroupID"] != null)//Are they coming here with a URL var? If so, build content object
{
List<Item> itemList = ItemManager.getItemsByGroupID(Request.QueryString["GroupID"].ToString());
dlMine.DataSource = itemList.Take(15);
dlMine.DataBind();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
dataBindList();
UpdatePanel1.Update();
}
protected void Item_Command(Object sender, DataListCommandEventArgs e)
{
if (e.CommandName == "Revalue")
{
Person p = (Person)Session["Person"];
foreach (DataListItem item in dlMine.Items)
{
string textBoxText = ((TextBox)item.FindControl("txtNewValue")).Text;
Utilities.writeLog("txtNewValue: " + textBoxText, 1);
}
dataBindList();
UpdatePanel1.Update();
}
}
You're rebinding the DataList every time the Timer ticks. All changes in the ItemTemplates of the DataList will be lost on postback.
Why not use Javascript to "pause" the timer whenver one of the textboxes gains focus. This will prevent the Timer from firing and let users finish entering text. Once they leave the textbox of "onblur" then you can restart the timer.
Update
The following will take a bit of effort to make it happen but you can do something like:
When the Timer posts back, before rebinding, iterate over the DataList while searching for textboxes with text in them. Something like:
foreach (DataListItem item in dlMine.Items)
{
//find the textbox control and check for text
}
At this point, you'll know which rows need there textboxes repopulated. Store this information in a hashtable.
In the DataList ItemDataBound event, check each rowID against the hashtable to see if its corresponding textbox exists. If so, repopulate the textbox in the DataList row.
Are you initializing the TextBbox value in your code-behind, perhaps in Page_Load or another page method?
TextBox1.Text = "";
If so, that code is executing on every timer event. You can prevent that like this:
if (! IsPostback) {
TextBox1.Text = "";
}
The first request that hits an ASP.NET page is usually an HTTP GET request, while ASP.NET buttons and update panel events issue HTTP POST requests. So the code above will clear TextBox1 the first time you access the page, but leave the value alone when receiving requests from itself. (If you really are setting the text box's value to its default - empty - you could just remove the initialization code.)

Getting control that fired postback in page_init

I have a gridview that includes dynamically created dropdownlist. When changing the dropdown values and doing a mass update on the grid (btnUpdate.click), I have to create the controls in the page init so they will be available to the viewstate. However, I have several other buttons that also cause a postback and I don't want to create the controls in the page init, but rather later in the button click events.
How can I tell which control fired the postback while in page_init? __EVENTTARGET = "" and request.params("btnUpdate") is nothing
It is possible to determine which control caused a PostBack by looking at Request.Form["__EVENTTARGET"]. The problem with this is that button ids will not show unless you set their UseSubmitBehavior to false. Here's an example:
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
switch (Request.Form["__EVENTTARGET"].ToString())
{
case "ddlOne":
break;
case "btnOne":
break;
case "btnTwo":
break;
}
}
}
.aspx
<form id="form1" runat="server">
<asp:DropDownList ID="ddlOne" AutoPostBack="true" runat="server">
<asp:ListItem Text="One" Value="One" />
<asp:ListItem Text="Two" Value="Two" />
</asp:DropDownList>
<asp:Button ID="btnOne" Text="One" UseSubmitBehavior="false" runat="server" />
<asp:Button ID="btnTwo" Text="Two" UseSubmitBehavior="false" runat="server" />
</form>

Resources