Showing posts with label gridview. Show all posts
Showing posts with label gridview. Show all posts

Wednesday, March 28, 2012

PostBack is happening even after using Update Panel and Script Manager

Hi,

I have a ASP.NET web application. I have a gridview and using a RowDataBound andRaisePostBackEventevent for getting the GridView details in the controls below like textboxes, dropdown etc. Now i am using Ajax Extensions controls like Update Panel and Script manager to avoid a postback happening when the GridView row is clicked. Even after implementing them postback is happening. Please see the code bits and let me know if i am missing somewhere.

UI

<asp

:ScriptManagerID="ScriptManager1"runat="server"EnablePartialRendering="true"></asp:ScriptManager>

<

asp:UpdatePanelid="UpdatePanel1"runat="server"UpdateMode="Conditional">

<contenttemplate>

<asp:GridViewID="GridView1"runat="server"OnRowDataBound="GridView1_RowDataBound"CssClass="sampletable"AlternatingRowStyle-CssClass="d1"ShowHeader="true"ShowFooter="false"AllowPaging="true"AllowSorting="true"AutoGenerateColumns="false"DataKeyNames="ProjectID"Width="100%"PageSize="5"><Columns>

<asp:BoundFieldVisible="false"HeaderText="Project ID"DataField="ProjectID"SortExpression="ProjectID"/><asp:BoundFieldHeaderText="Project Name"DataField="ProjectName"SortExpression="ProjectName"/><asp:BoundFieldHeaderText="Site Name"DataField="SiteName"SortExpression="SiteName"/></Columns></asp:GridView><asp:LabelID="Label1"runat="server"Text="Label"></asp:Label><asp:TextBoxID="TextBox1"runat="server"></asp:TextBox><asp:ButtonID="Button1"runat="server"Text="Button"/>

</

contenttemplate>

<

Triggers>

<

asp:AsyncPostBackTriggerControlID="GridView1"EventName="RowDataBound"/>

</

Triggers>

</

asp:UpdatePanel>

And theCode behind for RowDatabound event is

protected

void GridView1_RowDataBound(object sender,GridViewRowEventArgs e)

{

try

{

if (!((e.Row.RowType ==DataControlRowType.Pager) || (e.Row.RowType ==DataControlRowType.Header) || (e.Row.RowType ==DataControlRowType.Footer)))

{

System.Web.UI.

ClientScriptManager cs = Page.ClientScript;//Assign Row Index. This row index used in finding the ID of the clicked rowint intRowIndex = e.Row.RowIndex;

e.Row.Attributes.Add(

"onClick", cs.GetPostBackEventReference(this, intRowIndex.ToString().Trim()));

e.Row.Attributes.Add(

"onKeyDown","if( event.keyCode == 13 ) " + cs.GetPostBackEventReference(this,"KEYDOWN" +"$" + e.Row.DataItemIndex.ToString().Trim()));

}

}

catch (System.Exception ex)

{

//OnError(ex);

}

}

The code looks good, did you try a easy test to see if the postback is hidden?

http://alpascual.com/blog/al/archive/2006/12/21/Code-Snip-_2200_AJAX-Timer_2200_.aspx

Try the sample below and let me know if you see the postback


Thanks for the Quick Response.

But i could not get exactly what you want to convey.

regards,

Parimal


Ok, wrap a asp:button around an updatepanel and let me know if you see the postback

Hi,

The button is working fine without any post back. The Post back is happening when Grid Row is clicked as it call the RaisePostBack event to get the Row details. That event is coded as we have not used any command template in Grid.

regards,

Parimal


OnRowDatabound would not make sense for an async trigger. The user clicking the row and getting a postback via the javascript you added to the onclick is not the same. If you take out the trigger and just add ChildrenAsTriggers="true" to the UpdatePanel it would probably work as you expect.

One other thing - in this code:

"onClick", cs.GetPostBackEventReference(this, intRowIndex.ToString().Trim()));

e.Row.Attributes.Add(

"onKeyDown","if( event.keyCode == 13 ) " + cs.GetPostBackEventReference(this,"KEYDOWN" +"$" + e.Row.DataItemIndex.ToString().Trim()));

Change "this" to GridView1. You want to create a postback for your gridview, not the whole page. Since you're creating a custom postback you'll also need to register for event validation, or disable event validation in your page.


Thanks for the response. But still post back is happening. I will explain in details

1. I have a Gridview RowDataBound event which fires when Data is bounded to Grid.

2. I have aRaisePostBackEvent which fires when the row in the Grid is selected and this causes the Post Back event.

3. Aslo my UserControl is implementingIPostBackEventHandler interface.

Thanks in Advance,

Parimal

postback inside modalpopupextender

I want to show a modalpopupextender that contains: a textbox ,A button, gridview, ok button , close button: when the user click on A button the gridview must be populated , I need this behavior inside the modalpopupextender but it seems like modalpopupextender does not support any control that make a postback, How can I manage this??

Best Regards

Joseph

I already have done this what you need to do is,

let say. btnSearch popups your ModalpopupExtender,

when you click in side the control do one thing only in the code behind, of that click event either grid pageindexchange, sortiung, any button click in the last. that is.

ModalPopupExtender1.Show()

it will keep showing the popup until you click close button or call a method.

ModalPopupExtender1.Hide()

It is trial and tested, even I have done more than this in my application.

IF THIS MAKES ANSWER PLEASE CLICK ANSWER ON MY POSTING

Regards,


Hi Killerjocker,

My understanding of your issue is that you want to show some controls include the GridView and generate(update) the content inside it when click on the Button which is associated with the ModalPopupExtender. If I have misunderstood, please feel free to let me know.

In my opnion, I think the easiest way for your situation is adding a UpdatePanel into the Panel which is associated with the ModalPopupExtender and the GridView is put inside the added UpdatePanel. When user click on the Button, the UpdatePanel will be refreshed by sending a asynchronous post and then the shows the ModalPopupExtender. Here is a sample:

<%@. Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server"
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<style>
.modalBackground {
background-color:Gray;
filter:alpha(opacity=70);
opacity:0.7;
}

.modalPopup {
background-color:#FFD9D5;
border-width:3px;
border-style:solid;
border-color:Gray;
padding:3px;
width:250px;
}
</style>

</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="Button2" runat="server" Text="Button" Enabled="false" style="display:none"/>
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" Height="50px" Width="235px" style="display:none" DefaultButton="Button4">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<%=DateTime.Now.ToString()%>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" Text="Cancel" />
<asp:Button ID="Button4" runat="server" Text="Button" />
</asp:Panel>

<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button2" PopupControlID="Panel1" CancelControlID="Button1" DropShadow="true" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
<input id="Button3" type="button" value="Click Me" onclick="showModalPopup()"/>
<script type="text/javascript" language="javascript">
function showModalPopup(){
__doPostBack('<%=UpdatePanel1.UniqueID%>','');
$find("<%= this.ModalPopupExtender1.ClientID%>").show();
}
</script>
</form>
</body>
</html>

I hope this help.

Best regards,

Jonathan

PostBack Problem, Need Help.

I have a page with a drop down that drives a gridview. Now whatever is selected the drop down will drive whats shown in the gridview. The page loads fine and the default value in the drop down loads the gridview fine. Now on each row in the gridview I have an edit button to edit that row. I use a modal popup to edit that row and save it. The modal works great and updates a row. Here is where the problem happens, if I change the drop down to a different value the gridview updates, I edit the row and the modal pop is ok and saves...but without changing the drop down again if I try to edit another row I get this error...

--------
Windows Internet Explorer
--------
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@dotnet.itags.org. 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.
--------
OK
--------

Now I have tried adding that attrbute to the page tag and it still does not work...it gives me a similar error than the above one. I assume it has something to do with having all these postbacks and the modal is causing one while so is the edit button and they are conflicting somehow...anyway, any direction or solution would great. Let me know if anyone needs to see some code.

Hi Horizon,

In your modal popup, do you make partial or full postback when you update the datagrid row?

If you make partial postback, there is chance the server does not know all about this partial update, especially if you modify or update portions of your page, so by the next time you try to issue partial postback the server will complain about invalid postback event arguments.

It works if you change the dropdown because the dropdown issues full postback so the server now knows about all modifications on your page.

Is it an option to issue a full postback when you update the rows in the datagrid?

If your application does not require high grades of security, you could turn off the enableEventValidation attribute globally for your application (in web.config file).

Probably some ASPX and code-behind code would be helpful here to see how exactly you do the postbacks and updates on your page...

Kind regards,

sbogus.


Thanks you lead me on the right path, I added this to the load event...

ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnSaveRankings);

What this does is cause a full post back on the page now when I click btnSaveRankings which is in my modal panel. Though know its not saving state on my drop down...it reverts it back to the value as if you just came into the site...I am going to post my aspx and aspx.cs file...

<%@. Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="PowerRankingsAjax.admin.index" %><%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxControlToolkit" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Add/Edit Power Rankings</title> <link href="../ModalDialogs.css" rel="stylesheet" type="text/css" /></head><body> <form id="form1" runat="server"> <div> <asp:Label ID="lblError" runat="server" Text=""></asp:Label> <ajaxControlToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxControlToolkit:ToolkitScriptManager> Edit Past Issues <br /> Select Issue: <asp:DropDownList ID="ddlIssue" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlIssue_SelectedIndexChanged"></asp:DropDownList> <br /> <asp:UpdatePanel ID="uEditPanel" runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional"> <ContentTemplate> <asp:GridView ID="EditPowerRankings" runat="server" AutoGenerateColumns="false" OnRowCreated="EditPowerRankings_OnRowCreated" > <Columns><asp:TemplateField ShowHeader="False"><ItemTemplate> <asp:Button ID="btnEdit" runat="server" Text="Edit" OnClick="btnEdit_Click" CausesValidation="false" /></ItemTemplate></asp:TemplateField><asp:BoundField DataField="pid" /><asp:BoundField DataField="teamabbr" /><asp:BoundField DataField="team" HeaderText="Team" SortExpression="team" /><asp:BoundField DataField="rank" HeaderText="Rank" SortExpression="rank" /><asp:BoundField DataField="comment" HeaderText="Comment" SortExpression="comment" /></Columns> </asp:GridView><!--cheesy button for the modal popups target control--> <asp:Button ID="btnHiddenRankings" runat="server" style="display: none" /> <ajaxControlToolkit:ModalPopupExtender ID="mpeRankings" runat="server" TargetControlID="btnHiddenRankings" PopupControlID="pnlRankings" CancelControlID="btnCancelRankings" BackgroundCssClass="modalBackground" Drag="true" > </ajaxControlToolkit:ModalPopupExtender> <asp:Panel ID="pnlRankings" runat="server" CssClass="modalBox" Style="display: none;" Width="500px"><asp:Panel ID="RankingsCaption" runat="server" CssClass="caption" Style="margin-bottom: 10px;">Edit Rankings</asp:Panel> <asp:HiddenField ID="hidRankEditIndex" runat="server" Value="-1" /><div class="divCol"></div><div class="divColLast"> <asp:Image ID="imgTeam" runat="server" />  <asp:Label ID="lblTeamName" runat="server" Text=""></asp:Label></div><div class="clearer"></div><div class="divCol">Rank:</div><div class="divColLast">   <asp:DropDownList ID="ddlEditRank" runat="server"> <asp:ListItem>1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> <asp:ListItem>4</asp:ListItem> <asp:ListItem>5</asp:ListItem> <asp:ListItem>6</asp:ListItem> <asp:ListItem>7</asp:ListItem> <asp:ListItem>8</asp:ListItem> <asp:ListItem>9</asp:ListItem> <asp:ListItem>10</asp:ListItem> <asp:ListItem>11</asp:ListItem> <asp:ListItem>12</asp:ListItem> <asp:ListItem>13</asp:ListItem> <asp:ListItem>14</asp:ListItem> <asp:ListItem>15</asp:ListItem> <asp:ListItem>16</asp:ListItem> <asp:ListItem>17</asp:ListItem> <asp:ListItem>18</asp:ListItem> <asp:ListItem>19</asp:ListItem> <asp:ListItem>20</asp:ListItem> <asp:ListItem>21</asp:ListItem> <asp:ListItem>22</asp:ListItem> <asp:ListItem>23</asp:ListItem> <asp:ListItem>24</asp:ListItem> <asp:ListItem>25</asp:ListItem> <asp:ListItem>26</asp:ListItem> <asp:ListItem>27</asp:ListItem> <asp:ListItem>28</asp:ListItem> <asp:ListItem>29</asp:ListItem> <asp:ListItem>30</asp:ListItem> </asp:DropDownList></div><div class="clearer"></div><div class="divCol">Comments:</div><div class="divColLast"> <asp:TextBox ID="txtComment" runat="server" TextMode="MultiLine" MaxLength="500" Width="480" Height="200"></asp:TextBox></div><div class="clearer"></div><div style="white-space: nowrap; text-align: center;"> <asp:Button ID="btnSaveRankings" runat="server" Text="Save" OnClick="btnSaveRankings_Click" CausesValidation="true" /> <asp:Button ID="btnCancelRankings" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancelRankings_Click" /></div></asp:Panel> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="ddlIssue" EventName="SelectedIndexChanged" /> </Triggers> </asp:UpdatePanel> </div> </form></body></html>

cs file...

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;namespace PowerRankingsAjax.admin{public partialclass index : System.Web.UI.Page { powerrankings oPowerrankings =new powerrankings(); DataSet ds =new DataSet();public String strWeek;public int intCountVal;protected void Page_Load(object sender, EventArgs e) { ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnSaveRankings);if (oPowerrankings.ConnectToDatabase(lblError) ==true) {if (!Page.IsPostBack) {//GetWeek GetWeek(); BuildEditList(); BuildEditGrid(strWeek); } } ds.Dispose(); }protected void GetWeek() {//Current Week strWeek = oPowerrankings.GetMaxWeek(ds, lblError); }protected void BuildEditList() { ddlIssue.DataSource = ds.Tables[oPowerrankings.GetAllWeeks(ds, lblError).ToString()]; ddlIssue.DataTextField ="week"; ddlIssue.DataValueField ="week"; ddlIssue.DataBind(); intCountVal = oPowerrankings.GetHolder(ds, lblError);if(intCountVal > 0) { ListItem li =new ListItem("Edit","edit"); ddlIssue.Items.Add(li); }else { ListItem li =new ListItem("New","new"); ddlIssue.Items.Add(li); } lblError.Text = intCountVal.ToString();//ddlIssue.SelectedValue = strWeek; }protected void BuildEditGrid(string strWeek) { EditPowerRankings.DataSource = ds.Tables[oPowerrankings.GetEditPowerRankings(strWeek, ds, lblError).ToString()]; EditPowerRankings.DataBind(); }protected void ddlIssue_SelectedIndexChanged(object sender, EventArgs e) { strWeek = ddlIssue.SelectedValue;if (oPowerrankings.isNumeric(strWeek, System.Globalization.NumberStyles.Integer)) { BuildEditGrid(strWeek); }else { } }protected void EditPowerRankings_OnRowCreated(object sender, GridViewRowEventArgs e) { e.Row.Cells[1].Visible =false; e.Row.Cells[2].Visible =false; }protected void btnSaveRankings_Click(object sender, EventArgs e) { oPowerrankings.UpdatePowerRankings(Convert.ToInt16(hidRankEditIndex.Value), Convert.ToInt16(ddlEditRank.SelectedValue), txtComment.Text, lblError); mpeRankings.Hide(); strWeek = ddlIssue.SelectedValue; BuildEditList(); BuildEditGrid(strWeek); uEditPanel.Update(); }protected void btnCancelRankings_Click(object sender, EventArgs e) { mpeRankings.Hide(); }protected void btnEdit_Click(object sender, EventArgs e) { Button btnEdit = senderas Button; GridViewRow row = (GridViewRow)btnEdit.NamingContainer; hidRankEditIndex.Value = row.Cells[1].Text; imgTeam.ImageUrl ="../images/" + row.Cells[2].Text +".gif"; lblTeamName.Text = row.Cells[3].Text; ddlEditRank.SelectedValue = row.Cells[4].Text; txtComment.Text = row.Cells[5].Text; uEditPanel.Update(); mpeRankings.Show(); } }}

Monday, March 26, 2012

Prevent CHECKBOX in Update Panel

Hi there,i'm using CHECKBOX in Gridview Template Panel, and My Gridview is under UpdatePanel. The update panel will be refresh every 3 second using timer. how to prevent CHECKBOX from 'unchecking' when the user have already check the CHECKBOX ?Thanks.

Hi,

can you identify if it is due to slowly loading update panel or checkbox just loses its checked state on postback?

You can place just a button anywher eon the page (disable your timer before) and see if checkbox loses its checked value when you click this button.

-yuriy


The CHECKBOX just loses its checked state. I dont think palce a button anywhere is the solution for the application, since it'll have so much button. any ideas ?Thanks.

Hi,

an approach would be saving the checked boxes in an hidden field in the page. When a postback occurs, you parse the hidden field and extract the info about the checked boxes.

Since the GridView might be bound to different data each time, you have to associate an ID to each checkbox. The ID might be that of a database row, for example.

Then, when you're binding the GridView, you check whether the ID is in the list of checked boxes. If it is, you select the corresponding checkbox.

Sounds little complicated, but it should work.

Previous rows display when a new row add in GridView (in UpdatePanel) after hitting enter

I am having a problem in GridView using UpdatePanel. I have UpdatePanel which contains a GridView. When I enter rows in GridView and refresh a page it remove rows from Grid and if I enter again it shows only new entered row, works fine.

But when I enter few rows in Grid then click on address bar hit enter on it, it removes the rows from Grid and when I again enter a row again then it shows new with previous rows.

Can anybody tell me where am I doing a mistake.

Thanks in advance.

It works fine in debug mode but when I deploy the application on server, it shows previous records with new record.

Any idea?

Thanks in advance.

Saturday, March 24, 2012

Problem displaying values in gridview using ajax

hi

I am using asp.net 2.0 version.and sql2005 database.

On my UpdateErrorLog.aspx page i have three dropdown.2nd dropdown is filled on basis of first and 3rd dropdown is filled on basis of second.On 3rd dropdown "onchange" event i have called javascript function"FetchDGContents()" defined in "AjaxScript.js" file using ajax.Ajax Request is send to page"AjaxServer.aspx" and i get the response from that page.Problem is coming when i am trying to use that response to display the data in gridview.Below i am writing the code for Ajax page,Design page and the javascript file.Error is mentioned in javascript file in FunctionFilltable() andCleartable().I have searched and found ,that the control name on page rendering is prefixed with its container name.So u can see in my code and in Javascript file the prefixed name is'ctl00_contentarea'.It is working fine for Dropdowns when i am accessing their values(below in code file u can see) but failed to do so for Gridview.Plz help me out.

Thanks is advance

Below Code ofUpdateErrorLog.aspx file-------

<%@dotnet.itags.org.PageLanguage="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeFile="UpdateErrorLog.aspx.cs"Inherits="UpdateErrorLog"Title="Untitled Page" %>

<asp:ContentContentPlaceHolderID="contentarea"Runat="Server">

<scriptsrc="js/filldropdown.js"type="text/javascript"></script>

<scriptsrc="js/AjaxScript.js"type="text/javascript"></script>//This is the file in which Prblem is coming

<divid="Headingtxt"class="containerheading">

Update Error Log</div>

<divid="formcontent"class="containerdiv">

<tablecellpadding="0"cellspacing="0"class="labelfont">

<tr>

<tdstyle="width: 65px; height: 30px">

<asp:LabelID="Label1"runat="server"Font-Names="Arial"Font-Size="X-Small"

Text="Project"></asp:Label></td>

<tdstyle="width: 100px; height: 30px">

<asp:DropDownListID="ProjectDropDown"runat="server"Width="179px">

</asp:DropDownList></td>

</tr>

<tr>

<tdstyle="width: 65px; height: 29px">

<asp:LabelID="Label2"runat="server"Font-Names="Arial"Font-Size="X-Small"

Text="WBS"></asp:Label></td>

<tdstyle="width: 100px; height: 29px">

<asp:DropDownListID="WBSDropDown"runat="server"Width="178px">

</asp:DropDownList></td>

</tr>

<tr>

<tdstyle="width: 65px; height: 34px;">

<asp:LabelID="Label3"runat="server"Font-Names="Arial"Font-Size="X-Small"

Text="Task"Width="32px"></asp:Label></td>

<tdstyle="width: 100px; height: 34px;">

<asp:DropDownListID="TaskDropDown"runat="server"Width="178px">

</asp:DropDownList></td>

</tr>

<tr>

<tdstyle="width: 65px; height: 28px">

</td>

<tdstyle="width: 100px; height: 28px"align="left">

<asp:ButtonID="BtnGo"runat="server"Text="Go"Width="47px"/></td>

</tr>

</table>

</div>

<divid="gridviewcontent"style="left: 175px; width: 515px; position: absolute; top: 265px;

height: 84px">

<asp:GridViewid="gverrorlog"style="Z-INDEX: 102; LEFT: -6px; POSITION: absolute; TOP: 1px"runat="server"

width="592px"CellPadding="3"GridLines="Both"BorderStyle="Inset"Font-Names="Arial"Font-Size="X-Small"Height="100px">

<HeaderStyleCssClass="colhead"BackColor="#FF8080"Font-Names="Arial"Font-Size="X-Small"></HeaderStyle>

<RowStyleBackColor="#FFC0C0"Font-Names="Arial"Font-Size="X-Small"/>

</asp:GridView>

<TABLEid="imgtbl"style="VISIBILITY:hidden"borderColor="#000000"cellSpacing="1"cellPadding="1"

width="96"bgColor="#ffffff"border="0">

<TR>

<TD></TD>

</TR>

</TABLE>

</div>

</asp:Content>

-------------------------------------------

Code forAjaxserver.aspx page----------

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

publicpartialclassAjaxServer : System.Web.UI.Page

{

#region Variables

SqlConnection con =newSqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

CommonClass objcommon =newCommonClass();

ErrorLogClass objerrlog=newErrorLogClass();

DataSet SelectLogDS =newDataSet();

string chString;

#endregion

protectedvoid Page_Load(object sender,EventArgs e)

{

if (!IsPostBack)

{

//getting querystring value from update errorlog page

string pid = Request.QueryString["PID"];

string wbsid = Request.QueryString["WBSID"];

string tid = Request.QueryString["TID"];if(Request.QueryString["FromUperrpage"]!=null)

{

Response.Clear();

SelectLogDS=objerrlog.SelectErrorLog(pid, wbsid, tid); //SelectErrorLog is the method defined in a class.

//If you want to test by showing the "Image for Process" for a long time, uncomment the below two lines and set the time

//Dim th As System.Threading.Thread

//th.Sleep(200)

chString = SelectLogDS.GetXml();

Response.Clear();

Response.ContentType ="text/xml";

Response.Write(chString);

Response.End();

}else

{

Response.Clear();

Response.End();

}

}

else

{

Response.Clear();

Response.End();

}

}

}

-----------------------------------

Code forAjaxScript.js ------------------------

// This creates a XMLRequest (ActiveXObject) to be sent to the server

var XmlReq;

function CreateXmlReq()

{

try

{

XmlReq =new ActiveXObject("Msxml2.XMLHTTP");

}

catch(e)

{

try

{

XmlReq =new ActiveXObject("Microsoft.XMLHTTP");

}

catch(oc)

{

XmlReq =null;

}

}

if(!XmlReq &&typeof XMLHttpRequest !="undefined")

{

XmlReq =new XMLHttpRequest();

}

}

//This fucntion is to send the choice into the AJAX Server page for processing

function FetchDGContents()

{

//Starts displaying the Process Image table

imgtbl.style.visibility ='visible';var requestUrl ="AjaxServer.aspx?FromUperrpage=true&PID=" + document.getElementById("ctl00_contentarea_ProjectDropDown").value +"&WBSID=" + document.getElementById("ctl00_contentarea_WBSDropDown").value +"&TID=" + document.getElementById("ctl00_contentarea_TaskDropDown").value;

CreateXmlReq();

if(XmlReq)

{

XmlReq.onreadystatechange = HandleResponse;

XmlReq.open("GET", requestUrl,true);

XmlReq.send();

}

}

function HandleResponse()

{

if(XmlReq.readyState == 4)

{

if(XmlReq.status == 200)

{

// Before filling new contents into the DataGrid, clear the cotents by calling this function

//ClearTable();

// Fill the cleared Datagrid with new XML Reponse

FillTable(XmlReq.responseXML.documentElement);

// Hides the Process Image Table after displaying the contents

imgtbl.style.visibility ='hidden';

}

else

{

alert("There was a problem retrieving data from the server." );

}

}

}

//Fills the datagrid contents with the newly recieved Response content

function FillTable(serrorlog)

{

// Gets the response XML

var errlog = serrorlog.getElementsByTagName('NewDataSet');

// Gets the table type content present in the Response XML and gets the data into a variable tbl

var tbl = document.getElementById('ctl00_contentarea_gverrorlog').getElementsByTagName("tbody")[0];//Getting Error on this Line Error is: "Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object"

// Iterate through the table and add HTML Rows & contents into it.

for(var i=0;i<errlog.context.childNodes(0).parentNode.childNodes.length;i++)

{

// Create a HTML Row

var row = document.createElement("TR");

// Set the style

row.setAttribute("className","text");row.setAttribute("bgColor","#ECECEC");

// Iterate thorugh the columns of each row

for(var j=0;j<errlog.context.childNodes(0).childNodes.length;j++)

{

// Create a HTML DataColumn

var cell = document.createElement("TD");

// Store the cotents we got from Response XML into the column

cell.innerHTML = errlog.context.childNodes(i).childNodes(j).text;

// Append the new column into the current row

row.appendChild(cell);

}

// Append the current row into the HTML Table(i.e DataGrid)

tbl.appendChild(row)

}

}

// Clearing the existing contents of the Datagrid

function ClearTable()

{

var tbl = document.getElementById('ctl00_contentarea_gverrorlog').getElementsByTagName("tbody")[0]; //Getting Error on this Line Error is: "Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object"

var row = tbl.rows.lengthfor (var i=1,j=1;j<row;i++,j++)

{

if (tbl.rows.length == 2){i = 1;}

tbl.deleteRow(i);

if (tbl.rows.length == i) {i = 0;}

}

}

-----------------------------------

u cant access objects of a page by id in separate javascript file

try palacing the code in the aspx page in <Script> tag or

u need to send object of that control to javascript function


Its also not working if we write the code in aspx page instead of placing in seperate js file.

I am still getting same error.

thanks


document.getElementById('ctl00_contentarea_gverrorlog').

instead try using

document.getElementById('<%=Controlid.clientid %>').

i think Controlid is contentarea_gverrorlog


can you please tell me what is clientid in the above code?

i have tried using document.getElementById('<%=Controlid.clientid %>'). but same error is coming.At runtime

it is showing this statement as "document.getElementById('System.Web.UI.WebControls.GridView')"

thanks


Client Id is id of that contol on client side like "ct100_gridview1"

use like this if u have a problem

in javascript which is in the same aspx page that has control

document.getElementById('<%= Id %>').

and Code behind like this

publicpartialclassDisabling_controls : System.Web.UI.Page

{

//Declare Page level global variable

Public String Id=String.Empty;

protectedvoid Page_Load(object sender,EventArgs e)

{

Id = GridView1.ClientID.ToString();

}


Your suggested code is working fine.but still error is coming on the same line i.e

----var tbl = document.getElementById('<%= Id %>').getElementsByTagName("tbody")[0];

if i remove "getElementsByTagName("tbody")[0]" i get the varaible "tbl" valuenull and If I don' t remove

i get the above said error.I am unable to track why error is coming because this code is working fine

in .Net 1.0 version using datagrid.No solution till now...

this is the function in which error is coming...

function FillTable(serrorlog)

{

// Gets the response XML

var errlog = serrorlog.getElementsByTagName('TestErrorLog');

// Gets the table type content present in the Response XML and gets the data into a variable tbl

var tbl = document.getElementById('<%= Id %>').getElementsByTagName("tbody")[0];

// Iterate through the table and add HTML Rows & contents into it.

for(var i=0;i<errlog.context.childNodes(0).parentNode.childNodes.length;i++)

{

// Create a HTML Row

var row = document.createElement("TR");

// Set the style

row.setAttribute("className","text");row.setAttribute("bgColor","#ECECEC");

// Iterate thorugh the columns of each row

for(var j=0;j<errlog.context.childNodes(0).childNodes.length;j++)

{

// Create a HTML DataColumn

var cell = document.createElement("TD");

// Store the cotents we got from Response XML into the column

cell.innerHTML = errlog.context.childNodes(i).childNodes(j).text;

// Append the new column into the current row

row.appendChild(cell);

}

// Append the current row into the HTML Table(i.e DataGrid)

tbl.appendChild(row)

}

}


see view source to check whether datagrid is rendered with

tbody

tags for which you are searching


I m using gridview .In starting i have mentioned that i m working in .Net 2005.

in .Net 2003 the same code is working fine for datagrid.But as in .Net2005 i m using master

pages and therefore control name on rendering gets changed(which is not so in .Net2003).

Same code work fine in .Net2005 if i dont use master pages in my project.

thanks


hi

i got it! where the problem is.Problem i am not showing data in gridview on pageload that's why

the error is coming, because gridview is not rendered onpageload and i am trying to access it...

But then next problem is How to Do paging,sorting,and to define userdefined tempaltes if we use AJAX.

If there is some solution realted to this please give me.I m working in .Net 2005(gridview control).

thanks a lot for all ur help.


That's why i have asked u to see ViewSource whether it is rendered or not

Problem getting SelectedValue of Cascading DropDown inside a Gridview

I am trying to obtain the SelectedValue from a DropDownList which is controlled by a CascadingDropDown Control both of which are inside of a gridview. The cascading dropdowns are populating correctly. The SelectedValue is also set on these dropdowns in the OnRowDataBound event.

In the OnRowUpdating event, I am grabbing the dropdownlist's selected value from the updating row using:

string strID = ((

DropDownList)gvPositions.Rows[e.RowIndex].FindControl("ddlLineEdit")).SelectedValue;

When I do this, the value is always null.

I think it might be because you don't reference the cell but only the row. I have a similar example that does work:

DropDownList ddPanes = (DropDownList)grid.Rows[e.RowIndex].Cells[2].FindControl("ddPaneNames");

Hope it helps,

Joe
That was a good thought. I don't have to do that for the other controls in the row, but I tried it. Unfortunately that still give me null as well.
Can you post the markup for your gridview?

Here is my code:

<asp:GridView ID="gvPositions" runat="server" AutoGenerateColumns="False" Width="100%" OnRowEditing="gvEdit" OnRowCancelingEdit="gvCancel" OnRowUpdating="gvUpdate" OnRowCommand="gvItemCommand" OnRowDeleting="gvDelete" OnRowDataBound="gvRowDataBind"> <Columns> <asp:TemplateField HeaderText="positionID" Visible="False"> <ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.positionID")%>' ID="lblpositionID"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.positionID")%>' ID="lblpositionID"> </asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="TDA Version"> <ItemTemplate> <asp:Label runat="server" Text='<%# Eval("tdaName")%>' ID="lbltdaNameGrid"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" ID="lbltdaNameEdit" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.tdaName")%>'> </asp:Label> <asp:DropDownList ID="ddlTDANameEdit" runat="server" AutoPostBack="false" DataSource='<%# GetTDAList()%>' SelectedValue='<%# Eval("tdaVersionID")%>' DataTextField="tdaName" DataValueField="tdaVersionID" ></asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Paragraph"> <ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.paragraphTitle")%>' ID="lblParagraphNameGrid"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" ID="lblParagraphEdit" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.paragraphTitle")%>'> </asp:Label> <asp:DropDownList ID="ddlParagraphEdit" runat="server" AutoPostBack="false"></asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Line"> <ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.lineTitle")%>' ID="lbltitleGrid"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" ID="lbltitleEdit" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.lineTitle")%>'> </asp:Label> <asp:DropDownList ID="ddlLineEdit" runat="server" AutoPostBack="false"></asp:DropDownList> <cc1:CascadingDropDown ID="CascadingDropDownGridView" runat="server" SuppressValidationScript="true"> <cc1:CascadingDropDownProperties TargetControlID="ddlParagraphEdit" ServiceMethod="GetParagraphsByTDAID" ServicePath="~/AutoCompleteService.asmx" PromptText="Please select a paragraph" Category="tdaVersionID" ParentControlID="ddlTDANameEdit" /> <cc1:CascadingDropDownProperties TargetControlID="ddlLineEdit" ServiceMethod="GetLinesByParagraphID" ServicePath="~/AutoCompleteService.asmx" PromptText="Please select a line" Category="tdaParagraphID" ParentControlID="ddlParagraphEdit" /> </cc1:CascadingDropDown> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Directorate"> <ItemTemplate> <asp:Label runat="server" ID="lblDirectorate" Text='<%# DataBinder.Eval(Container, "DataItem.directorateSymbol")%>' width="100%"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList runat="server" id="ddlDirectorate" CssClass="label" Width="100%" DataSource='<%# GetDirectorateList()%>' SelectedIndex='<%# GetSelectedDirectorate(DataBinder.Eval(Container, "DataItem.directorateID").ToString())%>' DataTextField="directorateSymbol" DataValueField="directorateID"> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Division" ControlStyle-Width="100px"> <ItemTemplate> <asp:Label runat="server" ID="lblDivision" Text='<%# DataBinder.Eval(Container, "DataItem.officeSymbol")%>' width="100%"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList runat="server" id="ddlDivision" CssClass="label" Width="100%" DataSource='<%# GetDivisionList()%>' SelectedIndex='<%# GetSelectedDivision(DataBinder.Eval(Container, "DataItem.divisionID").ToString())%>' DataTextField="officeSymbol" DataValueField="divisionID"> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Start Date
<ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.dateStartText")%>' ID="lblGridDateStart"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtGridDateStart" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.dateStartText")%>'> </asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="End Date
<ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.dateEndText")%>' ID="lblGridDateEnd"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtGridDateEnd" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.dateEndText")%>'> </asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Current Position"> <ItemTemplate> <asp:CheckBox ID="chkbxPositionCurrentDisplay" runat="server" Checked='<%# DataBinder.Eval(Container, "DataItem.positionCurrent")%>' Enabled="false" /> </ItemTemplate> <EditItemTemplate> <asp:CheckBox ID="chkbxPositionCurrent" runat="server" Checked='<%# DataBinder.Eval(Container, "DataItem.positionCurrent")%>' /> </EditItemTemplate> </asp:TemplateField> <asp:CommandField ShowEditButton="True" CancelImageUrl="~/images/cancel.gif" ShowDeleteButton="True" DeleteImageUrl="~/images/delete.gif" EditImageUrl="~/images/edit.gif" UpdateImageUrl="~/images/save.gif" ButtonType="Image" /> </Columns> </asp:GridView>

The code I listed above us on a Web User Control called by another Web User Control which is called by a Web Form. I recreated the Gridview on a new page this morning with all the code behind and it worked.

So I am wondering if this has to do with when the Page_Load get called for each control. I would really like to get it to work on the control.


Could this be a symptom the cause of work item 640?

Problem in Binding Gridview through Modal popup

Hi,

I have a gridview inside a Panel which i being is shown byModalPopupExtender, and i am also using

DynamicServiceMethod -- to call a code_behind method , which inturn binds data from a data set to the gridview inside the panel.

But at the front end, i am unable to see any grid, all that i can see is just the empty pop-up(Modal). Need help on how

to bind dynamic data to modal pop.

thanks

Vishaal

It is the continuation of above problem

<ajaxToolkit:ModalPopupExtender

ID="ModalPopupExtender"runat="server"TargetControlID="imgBtnContinue"PopupControlID="pnlDiscounts"BackgroundCssClass="modalBackground"OkControlID="OkButton"OnOkScript="onOk()"CancelControlID="CancelButton"DropShadow="true"PopupDragHandleControlID="Panel3"DynamicServiceMethod="test()" (code behind method)DynamicControlID="gvDiscountDisplay" (grid inside panel) />

when i am clicking "imgBtnContinue" .. an javascript error is raised " Sys.ArgumentException: Value must not be null for Controls and Behaviors.

Parameter name:element


<ajaxToolkit:ModalPopupExtender

ID="ModalPopupExtender"

runat="server"

TargetControlID=" <Set target Id to some dummy control id>"

PopupControlID="pnlDiscounts"

BackgroundCssClass="modalBackground"

OkControlID="OkButton"

OnOkScript="onOk()"

CancelControlID="CancelButton"

DropShadow="true"

PopupDragHandleControlID="Panel3"/>

And in the actual Button click(Code-behind) invoke theModalPopupExtender.show()

-Vishaal

Wednesday, March 21, 2012

Problem in Reloadind a GridView using Timer

Hi,

Iam new to ASP.net. I have a problem; I need to reload a gridview forevery five seconds. So, I am using a timer control. In thetimerconrol_elapsed event, I am getting the datasource from thedatabase and binding it into the gridview. The problem is, theretrieved data from th database is not displaying in the gridview. Hereis my code,

Default.aspx:

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<atlas:ScriptManager EnablePartialRendering="true" ID="UpdateManager" runat="server"></atlas:ScriptManager>
<form id="form1" runat="server">
<div>

<atlas:UpdatePanel ID="upCityPanel" runat="server" Mode="Conditional">
<ContentTemplate>
<asp:GridView ID="GrdCity" runat="server" PageSize="5"></asp:GridView>
</ContentTemplate>
<Triggers>
<atlas:ControlEventTrigger ControlID="btn" EventName="Click" />
</Triggers>
</atlas:UpdatePanel>
<asp:Button runat="server" ID="btnReload" Text="Click to Reload" OnClick="ReloadGrid" />
</div>
</form>
</body>
</html
Default.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Timers;

public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("server=localhost/;database=new;user id=sa;password=;");

protected void Page_Load(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Enabled = true;
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
ReloadGrid(this, EventArgs.Empty);
}

protected void ReloadGrid(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select distinct(city) from authors", conn);
DataTable dt = new DataTable();
if (dt != null)
da.Fill(dt);
GrdCity.DataSource = dt;
GrdCity.DataBind();
}

}

Can anyone tell me what should I need to do? for getting the proper output.

Thanks in advance.

UdhayaOk, everything looks good but using a System.Timer, you need to use an AJax timer, just drag and drop from the toolbox INSIDE the UpdatePanel and everything is going to work great!
Thanks a lot Albert, it's working fine now. Thanks for your reply :-)

No worries, glad I can help.

Please make sure you mark my post as answered so other people having the same problem can find the solution.

Problem in RowCommand event of GridView within UpdatePanel

I have GridView and its EditItemTemplate has TextBox and in other column ImageButton.

I do defaultbutton this my ImageButton.

protected void GridView1_PreRender(object sender, EventArgs e)
{
GridViewRow editRow = (GridViewRow)this.GridView1.Rows[this.GridView1.EditIndex];

ImageButton imgBtnSave = editRow.FindControl("imgBtnSave")as ImageButton;

this.PanelGrid.DefaultButton = imgBtnSave.UniqueID;

}

my GridView1 is within panel - PanelGrid.

Before AJAX all worked very good. But in AJAX I have problem: in IE in textbox Enter works once only, in Firefox Enter don't work quite.

I did as they advised me:

I did function on JS:

function beforeDefaultClick( btnDefault )
{
__defaultFired = false;

btnDefault.disabled = true;

__doPostBack( btnDefault.name,'' );
}

For my ImageButton I write: OnClientClick="beforeDefaultClick( this )"

And now in IE all works good, but in Firefox event RowCommand of my GridView works twice !

I don't know how resolve this problem. Help me please.

Hi Alg42,

ALG42:

OnClientClick="beforeDefaultClick( this )"

Based on my experience, you should use OnClientClick="beforeDefaultClick( this ); return false;" instead.

Best regards,

Jonathan


Thank you.This works ! Smile