I want to bind gridview on treenode click.code works fine without error but in UI nothing changes, but when I use same code on button click, Gridview binds data properly.
My apsx code is
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="overflow: scroll; height: 450px;">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:TreeView ID="Folder_Treeview" runat="server" ShowLines="true" LeafNodeStyle-CssClass="childnode"
Style="" ForeColor="Blue" SelectedNodeStyle-ForeColor="Green" OnSelectedNodeChanged="Folder_Treeview_SelectedItemChanged">
</asp:TreeView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:GridView ID="GridView1" CssClass="grid" GridLines="None" ShowFooter="true" AllowPaging="true"
PageSize="5" AutoGenerateColumns="false" OnPageIndexChanging="GridView1_PageIndexChanging"
runat="server">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Length">
<ItemTemplate>
<asp:Label ID="lblLen" runat="server" Text='<%#Eval("Length")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Extention">
<ItemTemplate>
<asp:Label ID="lblFileType" runat="server" Text='<%#Eval("Extension")%>'>
</asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Creation Date & Time">
<ItemTemplate>
<asp:Label ID="lblDateTime" runat="server" Text='<%#Eval("CreationTime")%>'>
</asp:Label></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
<asp:Label Text="" ID="lblMsg" runat="server"></asp:Label></p>
CS Code:
protected void Folder_Treeview_SelectedItemChanged(object sender, EventArgs e)
{
TreeNode node = this.Folder_Treeview.SelectedNode;
SetFolderPath(node);
}
public void SetFolderPath(TreeNode node)
{
Session["ParentFolderId"] = node;
// System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(Server.MapPath("~/"));
string CurrNode = node.Text;
string separator = "\\";
Folder_Treeview.PathSeparator = Convert.ToChar(separator);
while (node.Parent != null)
{
CurrNode = node.Parent.Text + this.Folder_Treeview.PathSeparator + CurrNode;
node = node.Parent;
}
ViewState["Folder"] = CurrNode;
ViewState["FileType"] = "All";
GetFilesFromFolder();
}
private void GetFilesFromFolder()
{
// GET A LIST OF FILES FROM A SPECIFILED FOLDER.
DirectoryInfo objDir = new DirectoryInfo(Server.MapPath((string)ViewState["Folder"]));
FileInfo[] listfiles = objDir.GetFiles("*." + ((string)ViewState["FileType"] != "All" ?
ViewState["FileType"] : "*"));
if (listfiles.Length > 0)
{
// BIND THE LIST OF FILES (IF ANY) WITH GRIDVIEW.
GridView1.Visible = true;
GridView1.DataSource = listfiles;
GridView1.DataBind();
lblMsg.Text = listfiles.Length + " files found";
}
else
{
GridView1.Visible = false;
lblMsg.Text = "No files found";
}
}
OnSelectedNodeChanged method get called on node click, and all value sets properly but never get reflect.
Please help.
It's your update panel. The node event originates within the UpdatePanel so only the Update panel will get updated after postback. Keep in mind that the full Page lifecycle occurs, so the gridview does get databound, but only the content within the UpdatePanel will be refreshed.
Your options:
Add Folder_Treeview as a PostBack Trigger -or-
Get rid of the UpdatePanel altogether -or-
Move the Gridview inside the UpdatePanel ContentTemplate
Also a TreeView is one of several server controls that may not be compatible with an UpdatePanel:
The following ASP.NET controls are not compatible with partial-page updates, and are therefore not designed to work inside an UpdatePanel control:
TreeView control under several conditions. One is when callbacks are enabled that are not part of an asynchronous postback. Another is when you set styles directly as control properties instead of implicitly styling the control by using a reference to CSS styles. Another is when the EnableClientScript property is false (the default is true). Another is if you change the value of the EnableClientScript property between asynchronous postbacks. For more information, see TreeView Web Server Control Overview.
Menu control when you set styles directly as control properties instead of implicitly styling the control by using a reference to CSS styles. For more information, see Menu Control Overview.
FileUpload and HtmlInputFile controls when they are used to upload files as part of an asynchronous postback.
GridView and DetailsView controls when their EnableSortingAndPagingCallbacks property is set to true. The default is false.
Login, PasswordRecovery, ChangePassword, and CreateUserWizard controls whose contents have not been converted to editable templates.
The Substitution control.
Related
I have a listview that populates with data. This listview is inside a user control which sits inside a page called Preferences.aspx. Today I am handling click event on each row meaning that involves posting back to server.
Now, I have to put another user control on Preferences.aspx because there are group of more settings which need to be presented separately to users. I have added the new user control inside a separate tab on the page. This new tab has to be the first one to show when user lands on Preferences.aspx.
Now the problem is that when user goes to second tab (user control with listview) and click on a row, a postback occurs. This puts the user on the first tab (newly added user control).
So I wonder how can I get click event on a row without having to postback?
Any ideas or suggestions are welcome.I am working in Asp.Net with C#.
The code is:
Markup inside the user control:
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
... and so on
Markup inside Preferences.aspx:
<ABC:ListControl runat="server" ID="visitorListControl" CanSelect="true" IsMine="true" Recurring="false" OnVisitorSelected="ListControl_VisitorSelected" />
And code behind is:
protected string GetClickPostBack(int itemIndex)
{
if (CanSelect)
//return 0.ToString();
return "javascript: " + Page.ClientScript.GetPostBackEventReference(this, VisitorRowPrefix + itemIndex) + "; return false;";
else
return string.Empty;
}
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith(VisitorRowPrefix))
{
HandleRowClick(Convert.ToInt32(eventArgument.Substring(VisitorRowPrefix.Length)));
}
}
private void HandleRowClick(int index)
{
int CmgVisitorId = Constants.NotConfigured;
// bool IsHistoricVisitor = false;
// Visitor HistoricVisitor = new Visitor();
// Mark only the clicked row
... and so on.
Hook up to the grid button's click event using JavaScript/jQuery, and prevent theirs default behaviour (post-back) by 2 possible means:
return false;
e.preventDefault (jQuery only)
Example (using jQuery):
$('.button').click(function(event){
event.preventDefault();
//Write your client-side logic here
});
Description: If this method is called, the default action of the event
will not be triggered.
If I am understanding the issue properly, try an update panel.
Check out the documentation here.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
</ContentTemplate>
</asp:UpdatePanel>
First of all what I want to do is to pre select a value in my RadComboBox ,and if this value is not selected something else is selected then change the visibility to of some specific fields hidden.
My problem is that I'm able to make my pre select but somehow I can not change the status of my visibility for my specific fields when this pre selected value has changed.
What I have tired is to do it with a standard event OnSelectedIndexChanged but some how this is not triggering why so ever.. I have also added AutoPostBack=true as well as ViewStateMode=Enabled"
First my field's
Here comes my preslect as well here I would like to trigger the visibility change
<div class="formRowDiv">
<asp:Label ID="Activitylbl" runat="server" Text="Activity" CssClass="formLabel" />
<telerik:RadComboBox ID="rcbActivity" CssClass="rowForm" ViewStateMode="Enabled" runat="server" Width="260px" EmptyMessage="- Activity -"
DataTextField="ActivityId" DataValueField="ActivityId" AutoPostBack="true" OnSelectedIndexChanged="rcbActivity_SelectedIndexChanged">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ControlToValidate="rcbActivity"
ErrorMessage="Can not be empty" CssClass="rowFormValidation" />
</div>
What I want to hide:
<div class="formRowDiv">
<asp:Label ID="ActivityDescription" runat="server" Text="ActivityDescription" CssClass="formLabel" Visible="false"/>
<telerik:RadTextBox runat="server" ID="rtbActivityDescription" Wrap="true" Height="50" TextMode="MultiLine" AutoPostBack="true" CssClass="rowForm" ReadOnly="true" Visible="false" />
</div>
How I do my pre selection :
In my databind method that is called in my Page_Load
I firrst loop and then do a pre select
foreach (Activity item in ctx.Activity.OrderBy(l =>l.Code))
{
rcbActivity.Items.Add(new RadComboBoxItem(item.FullActivity, item.ActivityId.ToString()));
if (rcbActivity.Items.FindItemByValue("4") != null)
{
rcbActivity.SelectedIndex = rcbActivity.Items.IndexOf(rcbActivity.Items.FindItemByValue("4"));
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
}
Here is how I would hide my Fields
protected void rcbActivity_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
In case your controls are in an update panel then try removing it if the update panel is not so important and see if the changes u make to the controls in the server side are getting affected properly
I am trying to find a DropDownList control on the EditItemTemplate of a grid view, to populate it with results from a query before it is drawn, but the control is never found.
ddlParent == null
Always!
I may be missing something very obvious but i have tried about 8 different methods to get this find control working, but no matter what i do, it comes up null.
I have included both the ASP and the C#, the sql should not be important as i cant even reach the call!
ASP:
<asp:TemplateField SortExpression="LocationArea2.Name" HeaderText="Parent Location Area">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("LocationArea2.Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlParent" runat="server" AppendDataBoundItems="true" DataTextField="LocationArea2.Name"
DataValueField="ParentID" AutoPostBack="false" SelectedValue='<%# Bind("ParentID") %>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
C#:
protected void gvLocationArea_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gvLocationArea.EditIndex == e.Row.RowIndex)
{
DropDownList ddlParent = (DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("ddlParent");
if (ddlParent != null)
{
using (SalesSQLEntities db = new SalesSQLEntities())
{
ddlParent.DataSource = db.GetRecursiveAreaList(Convert.ToInt32(((TextBox)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("txtLocationAreaID")).Text), true);
ddlParent.DataBind();
ddlParent.Items.Add(new ListItem("* None", ""));
}
}
}
}
I know there is something missing here, the control is just never found no matter what i've tried!
Instead of doing a FindControl, use an offset index of the column in question and get the first control:
(DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].Cells[INDEX OF THE DDL].Controls[0]
I've an asp repeater which has some fields inside an ItemTemplate. Each item in the repeater has an "add to cart" asp:ImageButton and an invisible asp:Label as well. The code looks like this:
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="addToCart">
<HeaderTemplate>
<table id="displayTable">
</HeaderTemplate>
<ItemTemplate>
<td>
<!-- fields like name, description etc in the repeater are present; i've omitted to show them here-->
<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="addToCartImg" runat="server" ImageUrl="hi.jpg" Width="75px" Height="50px" />
</td>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
When a particular ImageButton in the repeater is clicked, I'm trying to display "added to cart" as the text of its corresponding Label, and make the clicked ImageButton Visible=false. I've tried using the OnItemCommand function for the ASP:Repeater. The method is "addToCart":
<>
void addToCart(Object Sender, RepeaterCommandEventArgs e)
{
Cart cart = new Cart();
cart.instrument_id = //id of product from repeater based on user click
String userName = Membership.GetUser().ToString();
cart.user_name = userName;
cart.quantity = 1;
var thisLbl = (Label)e.Item.FindControl("addedToCartLabel");
var thisImg = (ImageButton)e.Item.FindControl("addToCartImg");
try
{
database.Carts.InsertOnSubmit(cart);
database.SubmitChanges();
thisImg.Visible = false;
thisLbl.Text = "Added to Cart!";
thisLbl.Visible = true;
}
catch (Exception ex)
{
thisImg.Visible = false;
thisLbl.Text = "Processing failed;please try again later";
thisLbl.Visible = true; ;
}
}
The aspx page is populated properly. However, when I click on any of the ImageButtons in the repeater, I get the following error:
Server Error in '/mysite' Application.
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.
If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback
or callback data for validation.
Can someone help me with this?
May I suggest doing this with client-side javascript rather than a server-side call?
<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="addToCartImg" runat="server" ImageUrl="hi.jpg" Width="75px" Height="50px" />
becomes
<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="addToCartImg" runat="server" onclick="javascript:function() { this.this.style.display='none'; document.getElementById(this.parentNode.firstChild.id).style.display='block'; }" ImageUrl="hi.jpg" Width="75px" Height="50px" />
Here is what I am doing. I create two buttons in a header row of a gridview that i created. The buttons are +page and -page. When -page is hit I remove the paging and all the data goes down the page and -page disappears and +page is there.
Here comes my issue When I hit +page I must be double postbacking because one row of my data disappears. I will provide the code below. What can i do to fix this??
Dim bttnrempag As New Button
bttnrempag.ID = "bttnrempag"
bttnrempag.Text = " Paging"
bttnrempag.CssClass = "bttnMinEG"
bttnrempag.ValidationGroup = "alone"
bttnrempag.Attributes.Add("onclick", "return Paging('1')")
Dim bttnallowpag As New Button
bttnallowpag.ID = "bttnallowpag"
bttnallowpag.Text = " Paging"
bttnallowpag.ValidationGroup = "alone"
bttnallowpag.CssClass = "bttnAddEG"
bttnallowpag.Attributes.Add("onclick", "return Paging('0')")
---------------------How the buttons are added------------------------------------------
Dim row As New GridViewRow(-1, -1, DataControlRowType.Separator, DataControlRowState.Normal)
row.Cells.Add(cell)
cell.Controls.Add(bttnrempag) '36
cell.Controls.Add(bttnallowpag)
----------------------------------------------------------------------------------------
function Paging(remove) {
var gridView = $get('<%=Gridview1.ClientID %>');
var txt2 = $get('<%=TextBox2.ClientID %>');
if (remove == '1') {
txt2.value = '1';
__doPostBack('<%=UpdatePanel1.ClientID %>', '');
return false;
}
else {
txt2.value = '0';
__doPostBack('<%=UpdatePanel1.ClientID %>', '');
return false;
}
Edited
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate >
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource1" Font-Names="Comic Sans MS" Font-Size="XX-Small"
Caption = '<table border="" width="100%" cellpadding="3" cellspacing="0" bgcolor="#4A3C8C"><tr><td style = "font-size:X-large;font-family:Arial CE;color:White"><b>Ordering/Receiving Log</u></td></tr></table>'
Font-Bold="True" PageSize="15" >
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<Columns>
Bound Data
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<EmptyDataTemplate>
<head>
<meta http-equiv="refresh" content="5;URL=/Corporate_newpo/ReceivingLog.aspx?">
</head>
<script type="text/javascript" >
var count = 6;
var counter = setInterval("timer()", 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
//counter ended, do something here
return;
}
$get("timer").innerHTML = "The Table will Reload in " + count + " secs";
}
</script>
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large"
ForeColor="#993333" Text="No Data was Found for the Selected Filter"></asp:Label><br /><br />
<span id="timer" style="font-size:medium;color:blue"></span>
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingRowStyle BackColor="#F7F7F7" />
<PagerTemplate>
<small 12px""="" style="font-size:xx-small; padding-right">Go To Page</small>
<asp:DropDownList ID="ddlPageSelector" runat="server" AutoPostBack="true"
Font-Size="XX-Small" Height="19px" Width="36px">
</asp:DropDownList>
<asp:ImageButton ID="btnFirst" runat="server" CommandArgument="First"
CommandName="Page" SkinID="pagefirst" />
<asp:ImageButton ID="btnPrevious" runat="server" CommandArgument="Prev"
CommandName="Page" SkinID="pageprev" />
<asp:ImageButton ID="btnNext" runat="server" CommandArgument="Next"
CommandName="Page" SkinID="pagenext" />
<asp:ImageButton ID="btnLast" runat="server" CommandArgument="Last"
CommandName="Page" SkinID="pagelast" />
</PagerTemplate>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
So as you can see, when one or the other is hit I set a textbox to some value then i do a partial postback to my Gridview which is in that Updatepanel.
I suspect it's because you called the "__doPostBack" method. The buttons' normal default click behaviour will perform the Async postback, you probably made it perform another time. Try removing it and see how it goes.
Can you try to put the Click Attribute on the buttons in RowDataBound event declaration??
Cheers.
Try changing your <asp:ImageButtons> to be regular HTML <img> tags.
I've run into this sort of thing before which was hard to diagnose and even harder to explain. See here and here for some buggy behavior that might help. If you have <img> tags with blank src attributes, then the hyperlinks I provided likely explain the problem. If you do not have any blank <img> tags then keep reading for my work around.
In my specific case, it was only happening on some servers (at some client sites) but not others, so I couldn't find any concrete issues with the code. My workaround was to change my <asp:ImageButtons> to regular <img> tags with javascript click events that would call a function to perform the postback, much like your Paging() function.
For some reason, I have found that an <asp:ImageButton> with a client side onclick event of return:confirm('are you sure?'); will stop a postback if the confirm() returns false, however returning false the way you do in your Paging() function after manually calling a __doPostBack does not consistently stop the page from posting back a second time.
Please look at the html as it is rendered on the page:
Every time it's present
<img src=""/>
double postback can happen, for some browser...
This trouble could be resolved setting a default, blank, image for every button
<asp:ImageButton ImageUrl="~/Images/blank.gif"...>
Anyway, this command can be entered in Immediate Window if you put a breakpoint inside Page_Load and allow you to indentify the control that caused postback
Page.Request.Params["__EVENTTARGET"];
I've found a nice solution that works great. It does append it's own handler, but I guess that can be fixed too.
using System.Linq;
private void GridView_OnItemDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var buttons = e.Row.Cells.OfType<DataControlFieldCell>().SelectMany(item => item.Controls.OfType<ImageButton>());
foreach (ImageButton imageButton in buttons)
{
var argument = imageButton.CommandName + "$" + imageButton.CommandArgument;
imageButton.OnClientClick = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView, argument) + "; return false;";
}
}
}
Try this, (I don't know why you were using javascript):
bttnrempag.onclick += bttnrempag_Click;
protected void bttnrempag_Click(object sender, EventArgs e)
{
//handle the removal of paging or whatever.
}
You have to provide an image for your ImageButtons. Otherwise the HTML rendered will produce an <img src=""> tag and when this is rendered, it will cause a postback. Try it.