Button's cause validation property is set to false but still it fires validation - asp.net

I have a button in EmptyTempletField of gridview for which causevalidation property is set to false.
But when I try to add row in gridview from empty template field by clicking on that button, the button is not firing row command event. Moreover, it fires the validation. I have few validations which are grouped. But this button fires all validations irrespective of group. If I click on the button second time, then it fires the row command event. I can't understand what is happening..
Why button fires validation which it is not supposed to fire...???

It is not clear what is exaclty happening with your code. Anyway, it should be something similar to this
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDeletePicture" runat="server" CommandName="YOURCOMMAND" Text="command" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "YOURCOMMAND")
{
//your code
}
}
And read this article about GridView.RowCommand, which is helpful
Hope this helps

Related

Form data is saving and validation message is also displaying

We are using the callbackpanel for the validation of the Devexpress controls but what actually happening is :
If we click submit button without entering any thing in textboxes in the form. It is showing the validation messages but it is also saving the blank data to the database.
I want to know if validation message is showing then why event in backend is calling for saving data ?
Basically in DevExpress ASPxCallbackPanel, a Button Click does not trigger a Callback, it triggers a Postback that is the difference between an UpdatePanel and a CallbackPanel.
So you have to call the ASPxCallbackPanelClient.PerformCallback('PARAM'); instead.
You did not mention how you trigger the callback, you did not show how your ASPxButton code looks or how your ASPxCallbackPanel looks or how your Validator looks, so considering that please see code below that works very well in you scenario
All the controls as DX, including validators and buttons
<dx:ASPxCallbackPanel runat="server" ID="cbpDIActions" ClientInstanceName="cbpDIActions" OnCallback="cbpDIActions_Callback">
<panelcollection>
<dx:PanelContent>
<dx:ASPxSpinEdit ID="txtBuilFixtNoBathrooms" runat="server" ValidationSettings-RequiredField-IsRequired="true" ValidationSettings-ValidationGroup="SubmitValidation">
</dx:ASPxSpinEdit>
<dx:ASPxButton ID="btn" runat="server" AutoPostBack="false" Text="Process" UseSubmitBehavior="False"
ValidationSettings-ValidationGroup="SubmitValidation" CausesValidation="true"
>
<ClientSideEvents Click="function(s,e){
ASPxClientEdit.ValidateGroup('SubmitValidation');
if (ASPxClientEdit.AreEditorsValid()) {
if(!cbpDIActions.InCallback()) {
cbpDIActions.PerformCallback('PARAM');}
}
}" />
</dx:ASPxButton>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
And in the backend you put all your code in the callback event
protected void cbpDIActions_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e)
{
if (e.Parameter != null && e.Parameter.ToString() == "PARAM")
{
//PROCESS YOUR CODE
}
}

Two Buttons updating one item of a listview

I have two buttons in a ListView. With a click on the first Button I want to update the ListView-Item. With a click on the second button i want to update the ListView-Item and redirect to a different page. Both Buttons have a property CommandName="Update". I wanted to solve my problem with the CommandArgument-Property and the OnItemUpdated-Event, but I do not know how to get the value of this Property in the event.
<asp:ObjectDataSource ID="ods" runat="server" SelectMethod="Select" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter ..... />
</SelectParameters>
<UpdateParameters>
<asp:Parameters .... />
</UpdateParameters>
</asp:ObjectDataSource>
<asp:ListView ID="lv" runat="server" DataSourceID="ods" DataKeyNames="ID" OnItemUpdated="lv_OnItemUpdated">
<ItemTemplate>...</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnUpdate" runat="server" CommandName="Update"/>
<asp:Button ID="btnUpdate2" runat="server" CommandName="Update"/>
</EditItemTemplate>
</asp:ListView>
And in codebehind:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
...
}
Is it possible to decide in lv_OnItemUpdated which Button the user clicked?
I don't believe there is a way to distinguish which control issued the Update command, since sender is the ListView itself.
A workaround would be for you to give one button the CommandName "Update", and the other "UpdateRedirect".
The "UpdateRedirect" button will fire the ListView_ItemCommand event, and from there you can call ListView.UpdateItem, keeping your updating logic in there, and then redirect next.
Why do you insist on using the OnItemUpdated event?
Well there are 2 to 3 ways of doing it: One is of CommandArgument as:
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
and than on server side you can have:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
if(e.CommandName == "Sort")
//do you work and so on
}
or you can cast the sender as button and take it ID to see, which button was it:
((Button)sender)).ID
or you can get button ID as:
String ButtonID = Request["__EVENTTARGET"];
I hope it will help you in fixing your problem.
so you can have like:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
// either use e.CommandName
// or user ((Button)sender)).ID
}
Give each button a distinct name. Have the same event handling method in your code behind handle both button click events. Then check which button called the method.
EDIT: A workaround would be to use javascript to put the name of the clicked button into a hidden field on the form BEFORE it goes server side (using a client side script). Then in your Listview you could check the value of the hidden field to see which button was clicked.
Ok, yes, the itemcommand is what you want:
The lifecycle for an update or insert triggers both their native events AND the itemcommand event. The itemCommand event will occur prior to the itemUpdating or the itemInserting events.
So, you can create a boolean variable called called "bSecondButtonClicked" for example Add the command argument to both buttons with the Commandname='UPDATE". the e.command argument can be evaluated at the itemcommand event point. There set your Boolean variable (or however you implement it) to true. Then, at the itemupdating event, trigger your code based on the bSecondButtonClicked.
You need to get into the ItemCommand event of your ListView
protected void lstvw_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "new":
try
{
//e.CommandArgument
//e.CommandSource
// do your stuff here
}
catch (Exception ex)
{
}
break;
default:
break;
}
}

Prevent postback on server-side property change

I have a simple CalendarExtender (from AjaxControlToolkit) attached to a textbox.
<asp:TextBox ID="StartDateText" runat="server" MaxLength="10" Width="70px" AutoPostBack="True" OnTextChanged="StartDateText_TextChanged" />
<asp:ImageButton ID="ImageCalendarStartDate" runat="server" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" />
<asp:CalendarExtender ID="StartDateCalendarExtender" runat="server" TargetControlID="StartDateText" PopupButtonID="ImageCalendarStartDate" />
In order to control user input, I have the AutoPostBack set to True on the textbox, as well as a function on the TextChanged event (although TextChanged isn't the issue here).
In Page_Load, I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StartDateCalendarExtender.SelectedDate = DateTime.Now.AddDays(-1);
}
}
On opening the page, Page_Load sets the date, but the AutoPostBack triggers a postback right after Page_Load, calling it again with IsPostBack set to true.
Is there a server-side way to prevent this postback?
I tried setting the AutoPostBack property to false, changing the SelectedDate, and setting it back to true, but it keeps firing a postback.
The reason is that because you give the date on the extender, then the extender add it to the text box, then the text box trigger the post back.
How about try to set the text at the TextBox at the first place.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// remove that
// StartDateCalendarExtender.SelectedDate = DateTime.Now;
// and direct set it to the text box.
StartDateText.Text = DateTime.Now;
}
}
Maybe you need to format the DateTime the way you want it.

Getting an Instance of Dropdown list when clicking update on GridView in Asp.Net

I have a GridView with more than 30 columns. Most are plain controls but for some I have added a template control (DropDownList, Calendar and CheckBox control). Here is the aspx code for the control in question
<asp:TemplateField HeaderText="Field1 Caption" SortExpression="Field1">
<ItemTemplate>
<asp:Label ID="lblConstructionArea" runat="server" Text='<%# Eval("Field1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlField1" EnableViewState="true" runat="server"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
I wanted a dropdown to be shown on the column when a user clicked on Edit. So I add this code (and the above EditItemTemplate)
protected void gvData_RowEditing(object sender, GridViewEditEventArgs e)
{
string fieldOne = CommonUtils.ExtractControlValue(e,"lblField1",gvData);
gvData.SelectedIndex = e.NewEditIndex;
gvData.EditIndex = e.NewEditIndex;
gvData.DataBind();
BindGridDropDownData(e, CommonUtils.GetConstructionAreas() ,"ddlConstructionArea", constructionArea, "Field1", fieldOne);
}
In the above code I am getting the current available and passing it to another method so that when the dropdown is displayed the selected index can be shown accurately. After this I do a change on the dropdownlist and click on the "Update button" on the GridView and the following event is triggered
protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int rowEditIndex = e.RowIndex;
GridViewRow gRow = gvData.Rows[rowEditIndex];
DropDownList ddlConstructionArea = (DropDownList) gvData.Rows[rowEditIndex].FindControl("ddlConstructionArea"); //This does not work
ddlConstructionArea = (DropDownList)gRow.FindControl("ddlConstructionArea");//This does not work
ddlConstructionArea = (DropDownList)gvData.Rows[rowEditIndex].Cells[7].FindControl("ddlConstructionArea");//this does not work either
gvData.EditIndex = -1;//this works and the text boxes disappear
gvData.DataBind();//this works and the old data shows up on the gridview
}
I am curious as to how to do an update on a Grid where I have the binding is runtime.
Actually in the markup, you have given ID of dropdownlist as ddlField1 and in codebehind, you are reffering it as ddlConstructionArea. Is this is what causing the update not to function?
The problem was with the way the grid was being bound. I had written code to refresh the grid on page load and anytime I clicked on the Edit button the page was being refreshed and the grid binding was getting triggered instead of the updating event. I removed the code refreshing the grid on page load and put it in the places where it is needed and the order of events were getting triggered the way I would want it to and the update worked perfectly without a problem.

ASP.Net repeater Item Command not getting fired

OK, I've used repeaters literally hundreds of times without problems but something has gone awry today. I have a repeater and I'm subscribing to the itemCommand event, but when my command runs, the page posts back but the event isn't fired.
To get around this I'm having to do my databinding on each postback.
My repeater looks like this:
<asp:Repeater id="MyRepeater" runat="server" onitemcommand="MyRepeater_ItemCommand">
<ItemTemplate>
<li>
<asp:Label id="Label" runat="server" />
<asp:LinkButton id="LinkButton1" runat="server" commandname="Complete" commandargument='<%# Eval("MyID") %>' text='<%# Eval("Title") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
and my codebehind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetupPage();
}
}
private void SetupPage()
{
// Do other stuff
MyRepeater.DataSource = Repository.GetStuff()
MyRepeater.DataBind();
}
protected void MyRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
// Do all my stuff here
}
MyRepeater_ItemCommand is not getting called unless I comment out the if (!IsPostBack) line. Once that is commented out and the repeater is getting databound on each postback it works OK. I've done this in so many other pages but on this on it just doesn't seem to work.
Anyone else come across this behaviour or have a solution?
Most likely, you have disabled ViewState for the page.
The reason is that when you execute the postback, all the controls in the repeater are rebuild from the data in the viewstate normally. Then the object that should receive the event is identified based on the ID of the control, and the event is routed.
If you disable the viewstate, the control tree is not rebuild during postback, and therefore the control that should receive the event does not exist in memory. So the event dies.
If you really want to disable the viewstate, but still want to receive the event, I have a workaround (and it's not dirty at all). I've long been thinking about writing a blog entry about it, so if you want, I can take a bit time off my normal chores, and describe it.
Edit: The workaround is described here: http://petesdotnet.blogspot.dk/2009/08/asp.html
Remove if (!IsPostBack) as this is preventing the repeater from rebinding,
and the item command event could not find the row after postback.
I have the same problem and aside from using update panel, I have a required field validator in my modal. I found out that the LinkButtons in my repeater triggers the requiredFieldValidor event and then I added CausesValidation="false" in the LinkButtons of my repeater. Works as expected.
I have this problem in a repeater when I use ImageButton ...
I have search the net for this solution when LinkButton work, but not ImageButton ...
Then I think, LinkButton work? so i will use it :)
<asp:LinkButton CommandName="Filter" CommandArgument='<%# Eval("ID") %>' Text="" runat="server" >
<asp:image imageurl='<%#Eval("Img") %>' runat="server"/>
</asp:LinkButton>
So, the image is inside the <A> tag
have fun :)
I removed PostBackUrl property in linkbutton and ItemCommand fired. I think postback runs first.
That may be you have set Validations on your page. So set an new attribute, causevaliation = "false" to Link button. M sure it will solve the problem
I had a similar issue - turned out some discreet validation controls were firing elsewhere on the page. It only took me a day to figure it out ...
I am not positive about this, but you might have to set the CommandName and optionally CommandArgument properties for the button causing the ItemCommand event. Otherwise ASP.NET would assume that there is no button on the page, which you'd like to fire the event. You can try that.
Plus, if you're not differentiating between command names, why not use each button's Click event instead? Just subscribe to those in the repeater's ItemCreated or ItemDataBound.
Try using Page_init instead of Page_load and that should fix the problem.
Try this:
protected void Page_Load(object sender, EventArgs e)
{
SetupPage();
}
If you use nested-repeater, you should rebind your inner repe
Here Is the code you have to use in code behind..
after PageLoad event,
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Bind Your Repeater here
rptUser();
}
now you can fire your Itemcommand..if you get Output please mark answer as right thanks
One other thing that it could be (as it just happened to me): if your databind takes place when your page is prerendered, it won't process the item command. Switch it to load or init and you'll be fine.

Resources