__EVENTTARGET Contains Invalid Control ID - asp.net

Googled variations of the title and everything was related to a null value.
I have an issue where the return value from Page.Request.Params["__EVENTTARGET"] duplicates the unique id of the control.
ctl00$MainContent$ActivityTabset$TabNewActivity$cbxActivityCode$ctl00$MainContent$ActivityTabset$TabNewActivity$cbxActivityCode
cbxActivityCode.UniqueID returns
ctl00$MainContent$ActivityTabset$TabNewActivity$cbxActivityCode
The following is the code that fails in the comparison. It is in the Page_Load event, and is the only code to execute right now if it is a postback.
string controlName = Page.Request.Params["__EVENTTARGET"];
if (cbxActivityCode.UniqueID == controlName)
{
ConfigureActivityUnits();
}
Here is the definition of the control
<obout:ComboBox ID="cbxActivityCode" runat="server"
DataSourceID="ObjectDataSourceDAOActivity"
FilterType="StartsWith" EmptyText="Select..."
AutoPostBack="true"
OnSelectedIndexChanged="cbxActivityCode_SelectedIndexChanged"
AllowCustomText="false" AutoValidate="true" DataValueField="Id"
DataTextField="Description" EnableViewState="true"
OpenOnFocus="true" MenuWidth="425" AllowEdit="False"
Width="300px">
</obout:ComboBox>
I am new to ASP.net and am wondering if it is possible one of the control attributes is causing this behavior?
Is it possibly a bug with the control?
Are there hooks in ASP.net where someone can manipulate a value which will effect Page.Request.Params["__EVENTTARGET"]? (This is a big messy legacy system, and I have no prior developers as a resource.)
If not any of the above, anyone have any ideas as to what could be causing this?

Related

Showing single error for multiple asp validators

I have a text box control in asp with 3 different validators. Each validator is getting its error message from the server, and each one validates different things.
My problem is that for some values, two or more validators are firing and I'm getting more then one error message.
I would like to make some kind of priority functionality, meaning that if the first validator is firing the other two will not. Is there any way to make the validator behave like that?
I've added some code sample:
<asp:RequiredFieldValidator ID="cvRequired" runat="server" Display="Dynamic"
ControlToValidate="txtBox" />
<asp:RegularExpressionValidator ID="cvFormat" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ValidationExpression="^([A-Za-z])+$" />
<asp:CustomValidator ID="cvCustom" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ClientValidationFunction="validateFunction" />
I want that the format validator and the custom validator will not fire if the required validator is invalid (actually, I just want them to not showing their error message).
As I said, the error messages are from the server, so I can't really join them to one custom validator. Also, the "validateFunction" is in another js file (for re-use).
Few logic options you got to think about,
(txtPhone) having three validators.
1.RangeValidator, 2.CustomValidator 3.Regexvalidator
Say,after validation (check what it returns if validation fails/passes) and act upon that.
if(rangevalidator1 != null)
{
...somecode...
}
I ll suggest you using javascript ..
you can use a single custom validator for all three validation and you put your code in if condition according to your need.
<asp:CustomValidator runat="server" ID="cstmStartDateValidater"
ToolTip="Start date cannot be greater than equal to end date/time or less than current date/time"
ErrorMessage="*" ControlToValidate="txtStartDateTime"
ForeColor="Red" ValidationGroup="vlgMessage" SetFocusOnError="true"
onservervalidate="cstmStartDateValidater_ServerValidate" ></asp:CustomValidator>
in the .cs page
protected void cstmStartDateValidater_ServerValidate(object source, ServerValidateEventArgs args)
{
if (CompareStartDate())
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
you can use following link for more information :
MSDN,
Code Project
hope these will help you .
Make use of ValidatorCalloutExtender control which is available in ajax control toolkit.
Place a separate ValidatorCalloutExtender across each control,you wish to validate it.

Setting complex members of a control inside a Repeater

TL;DR
The Control inside my Repeater requires special instantiation before it can be useful. How do I perform this special instantiation for each control as they are constructed by the repeater?
The Setup
I have three classes:
ComplexData.
Contains many public members of varying types, such as:
int favorite_integer
Food what_you_had_for_breakfast_this_morning
string capital_of_alaska
PhaseOfMoon when_magic_runes_will_reveal_themselves_on_the_mysterious_artifact
etc, etc, etc
ComplexDataDisplay
A control used to render an instance of ComplexData in an aesthetically pleasing way. Exposes a single public member, ComplexMember DataToDisplay. When the user sets DataToDisplay, the labels within the control will populate themselves with the appropriate data.
MultiComplexDataDisplay
A control that uses a Repeater to display multiple ComplexDataDisplays in a row. It contains a private List<ComplexData> datasToDisplay, which is the data source for the repeater. It provides two public methods, addComplexData(ComplexData) and emptyAllData(), which let the user manipulate datasToDisplay.
The Problem
During the data bind process, I don't know how to set each ComplexDataDisplay's DataToDisplay member.
It appears that controls within repeaters are normally populated from the front end, for example
<asp:Repeater runat="server" id="linkRepeater">
<%# getDescription(Container.DataItem) %>
</asp:Repeater>
As I understand it, during data bind, the repeater instantiates each anchor element, using whatever the data source is to set the href and description.
My attempt to replicate this behavior only led to a blank page:
<asp:Repeater runat="server" id="displayRepeater">
<ComplexDataDisplay id="dataDisplay" DataToDisplay="<%# Container.DataItem %>" runat="server"
</asp:Repeater>
The only other thing I can think to try is to modify ComplexDataDisplay so it has a public member for each member of ComplexData. Then within the repeater I can do:
<asp:Repeater runat="server" id="displayRepeater">
<ComplexDataDisplay id="dataDisplay" runat="server"
favorite_integer="<%# get_favorite_integer(Container.DataItem) %>"
what_you_had_for_breakfast_this_morning="<# get_what_you_had_for_breakfast_this_morning(Container.DataItem) %>"
<%--etc etc etc--%>
/>
</asp:Repeater>
This seems highly undesirable because for every member of ComplexData, I'll have to write a corresponding public member in ComplexDataDisplay, and a get_whatever(DataItem) method in MultiComplexDataDisplay. On top of that, I don't even know if it will work, because half of ComplexData's members are complex data types, which may or may not be settable in this way.
What I'm looking for in an answer
One of the following:
A direct answer to the question posed in the TLDR section - a way to perform special instantiation for each control in the repeater during databind, or a way to iterate through them shortly after the fact.
A recommendation on how to best restructure the code, such so that special instantiation is no longer necessary to display my many Complex Datas. I am willing to add/update/delete any class besides ComplexData, as I am obligated to maintain its interface as-is.
best practices/references/documentation related to my problem, which will guide me in finding a solution myself.
You can bind you child controls inside of ItemDataBound, I couldn't follow which objects get bound when so replace where needed:
<asp:Repeater runat="server" id="displayRepeater" OnItemDataBound="displayRepeater_ItemDataBound">
<uc1:ComplexDataDisplay id="dataDisplay" runat="server" />
</asp:Repeater>
protected void displayRepeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//get object bound to row
ComplexData c = (ComplexData)e.Item.DataItem;
//find the child control to bind
ComplexDataDisplay cds = (ComplexDataDisplay)e.Item.FindControl("dataDisplay");
//set properties or any other complex things you need to do
cds.DataToDisplay = c.ComplexMember;
cds.DataBind(); // if this control has repeaters, it's ItemDataBound will fire, repeat this process untill all your controls are bound properly
}
}

Page doesn't postback if it has validation control after deployment

I have a page with a RadioButtonList which should post back when the selection is changed. But because of RequiredFieldValidator on the page, the postback is not happening.
It is working fine on //localhost/ but not after deployment to production server.
The error on the page is:
'event' is null or not an object
Line: 126
Char: 5
Code: 0
URI: http://web-dev:90/aspnet_client/system_web/2_0_50727/WebUIValidation.js
A few things which I have already tried:
1) aspnet_client folder is in its proper place.
2) I have added Page.Validate() and if(Page.IsValid){} statements with the button on whose click the validation should happen.
3) The ValidatorCommonOnSubmit function in WebUIValidation.js file looks like this:
function ValidatorCommonOnSubmit() {
event.returnValue = !Page_BlockSubmit;
Page_BlockSubmit = false;
return event.returnValue;}
Can somebody help me with this? Any help would be appreciated. Thanks!!
you can group the required field validator related controls so that it wont effect the radio button list.
<asp:RequiredFieldValidator ID="rfv" runat="server" ValidationGroup="button1"
ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button1" ValidationGroup="button1" />
As far as your radio button list is not grouped under "button1" group, it will not have any problem.
Details here and here

Creating dynamic DataList controls with ID's based on bound data

As a workaround for the fact that asp:Checkboxes don't have values, I am attempting to dynamically create the ID's of checkboxes in a DataList so that it inserts the primary keys into the control ID. This is surprisingly difficult.
I have placed a PlaceHolder in my DataList ItemTemplate, then in the ItemCreated I create the checkboxes using string.Format("Checkbox{0}", DataBinder(e.Item.DataItem, "ID")). The problem is that this only works in a non-postback condition, as on postback the DataItem is null. And of course ItemDataBound isn't called on PostBack so that won't work either.
I can't seem to find a good way to handle this short of if (IsPostback) dataList.Bind(), which i don't think is a good way to do it.
Can anyone provide me with any alternatives here?
EDIT:
Some additional information. I just realized that part of the problem was because I actually have a DataList within a DataList. The reason DataItem is null is because there is no databinding on postback, and the child data is not saved to viewstate.
Basically, what i'm doing is This, although it's using a DataList rather than Repeater. So, on postback, the Children collection doesn't get set because ItemDataBound isn't called on postback.
EDIT2: To clarify, the problem is largely because of the nested datalists. I have to set the datasource of the nested datalist to a collection field of the first datalist's individual rows fields. On postback, there is no databinding, so it doesn't work.
You could use a similar technique to the one I wrote up in this answer - add a regular CheckBox, and a HiddenField control in the ItemTemplate, and bind the HiddenField to the primary key value e.g.
<ItemTemplate>
<tr>
<td>
<asp:CheckBox runat="server" ID="MyCheckBox" AutoPostBack="true" oncheckedchanged="MyCheckBox_CheckedChanged" />
<asp:HiddenField runat="server" id="DatabaseKeyHiddenField" Value='<%# Eval("DatabaseKey") %>' />
</td>
</tr>
</ItemTemplate>
protected void MyCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox selectedCheckBox;
DataListItem selectedDataListItem;
HiddenField databaseKeyHiddenField;
string databaseKey;
// Cast the sender object to a CheckBox
selectedCheckBox = (CheckBox)sender;
// Walk up the tree one level so we get the container for both controls
selectedDataListItem = (DataListItem)selectedCheckBox.Parent;
// Get the HiddenField control ...
databaseKeyHiddenField = (HiddenField)selectedDataListItem.FindControl("DatabaseKeyHiddenField");
// ... and read the value
databaseKey = databaseKeyHiddenField.Value;
// Go off and do a database update based on the key we now have
...
}
It's a bit of a workaround rather than exactly what you want to do, but it works!

ASP .NET with MySQL - use TINYINT with asp:Checkbox

For my ASP .NET webpage I am using a MySQL database with a TINYINT field to indicate a boolean (0/1) value.
Thanks to stackoverflow I was able to read the field value into a Listview as a asp:Checkbox.
<asp:CheckBox ID="freight_foundCheckbox" runat="server"
Checked='<%# Convert.ToBoolean(Eval("freight_found")) %>' />
What is challenging me now is how to reverse the transaction in the InsertItemTemplate or EditItemTemplate.
The listview textbox reads as:
<asp:TextBox ID="freight_foundTextBox" runat="server"
Text='<%# Bind("freight_found") %>' />
How do I bind a asp:Checkbox value back into the database as a integer value?
This web site link text was tremendously helpful in resolving this issue.
The key is to capture the value and convert it into a MySQL friendly format before writing to the database.
So for a insert set a ItemInserting event with this code:
CheckBox freightFound = (CheckBox)ListView2.InsertItem.FindControl("freight_foundCheckbox");
if (freightFound.Checked == true)
{
//true
e.Values["freight_found"] = 1;
}
else
{
//false
e.Values["freight_found"] = 0;
}
And then for a edit set a ItemUpdating event.
CheckBox freightFound = (CheckBox)ListView2.EditItem.FindControl("freight_foundCheckbox");
if (freightFound.Checked == true)
{
//true
e.NewValues["freight_found"] = 1;
}
else
{
//false
e.NewValues["freight_found"] = 0;
}
I know this is really old but I just spent a couple of hours trying to get this sorted.
in your UPDATE or INSERT statement you can use this
IF(?='True',1,0)
no need to change a bound checkboxfield to an item template or anything.
I'm not sure if it matters but I changed my parameter type to Boolean and as I now have it working I don't want to change it.
A little late here, but why not just bind it directly to the checkbox instead of a text field? No code behind handling needed that way. See below. MySQL tinyint(1) converts directly to .NET boolean and back when using the MySQL Connector/.NET.
<asp:CheckBox ID="freight_foundCheckbox" runat="server"
Checked='<%# Bind("freight_found") %>' />

Resources