Asp.net and Ext.Net validation - asp.net

Does anybody show me an example of ext.net validation? I want to mix asp.net and ext.net validation. Or use ext.net validation only.
I've already saw these examples http://examples.ext.net/#/Form/Validation/Custom_VType/ and http://examples.ext.net/#/Form/FormPanel/Validation/ but it's not enough.
Also, I wonder why the code bottom doesn't work. It throws an exception
"Page.IsValid cannot be called before validation has taken place. It
should be queried in the event handler for a control that has
CausesValidation=True and initiated the postback, or after a call to
Page.Validate"
<script runat="server">
void Button_Click(object sender, EventArgs e) {
// Display whether the page passed validation.
if (Page.IsValid) {
Label1.Text = "Page is valid.";
}
else {
Label1.Text = "Page is not valid!";
}
}
void ServerValidation(object source, ServerValidateEventArgs args) {
try {
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i % 2) == 0);
}
catch (Exception ex) {
args.IsValid = false;
}
}
</script>
<ext:Label ID="Label1" runat="server" Text="Enter an even number:" />
<br />
<ext:TextField ID="TextField1" runat="server" />
<asp:CustomValidator runat="server" ControlToValidate="TextField1" OnServerValidate="ServerValidation"
ErrorMessage="Not an even number!" />
<ext:Button runat="server" Text="Validate" >
<DirectEvents>
<Click OnEvent="Button_Click" />
</DirectEvents>
</ext:Button>

How about this sample? And in pastebin: http://pastebin.com/hGCjnNqh
<script runat="server">
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
Page.Validate();
}
void ServerValidation(object source, ServerValidateEventArgs args)
{
try
{
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i % 2) == 0);
}
catch (Exception ex)
{
args.IsValid = false;
}
}
void Button_Click(object sender, EventArgs e) {
// Display whether the page passed validation.
if (Page.IsValid) {
Label1.Text = "Page is valid.";
} else {
Label1.Text = "Page is not valid!";
}
}
<ext:ResourceManager ID="ResourceManager1" runat="server" />
<ext:Label ID="Label1" runat="server" Text="Enter an even number:" />
<br/>
<ext:TextField ID="TextField1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server"
ControlToValidate="TextField1"
OnServerValidate="ServerValidation"
ErrorMessage="Not an even number!" />
<ext:Button ID="Button1" runat="server" Text="Validate" AutoPostBack="false" CausesValidation="true">
<DirectEvents>
<Click OnEvent="Button_Click" />
</DirectEvents>
</ext:Button>

Use ext.net component inside ext.net formpanel you don t need to use asp net validation.

Related

Weird post back behavior on ASP.NET web form while refreshing

In an ASP.NET web form, I have two button controls and I have come across a weird scenario.
I have btnOpenAddRoleModal and btn2. when I click on btnOpenAddRoleModal, btnAddGlobalRoles becomes visible and then I click on btnAddGlobalRoles which performs some function.
Now when I press F5 to refresh the page, and because ASP.NET post-backs the page again on refresh, it does the post back as usual.
My problem is that it runs the click event handler of btnOpenAddRoleModal instead of btnAddGlobalRoles whereas the last button I clicked was btnAddGlobalRoles.
Anyone knows why this could be a case?
aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/MainTheme.Master" AutoEventWireup="true" CodeBehind="GlobalRoles.aspx.cs" Inherits="OPT.GlobalRoles" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<header style="overflow: auto;">
<h1 class="zs-left">Global Roles</h1>
<div class="zs-right">
<asp:Button ID="btnOpenAddRoleModal" runat="server" Text="Add User" CssClass="zs-button zs-button-action" OnClick="btnOpenAddRoleModal_Click" OnClientClick="return IncreasePostBackControlValue();" />
</div>
</header>
<section class="page-2cols" style="position: relative;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<h2 class="zs-inner-title">Roles</h2>
<p class="zs-search-button">
<span class="zs-input-icon zs-icon-search">
<asp:Label ID="lblSearchText" runat="server" Text="Search Roles " Style="font-weight: 700"></asp:Label>
<asp:TextBox ID="txtSearchText" runat="server" CssClass="zs-input" placehoder="Enter key words to search" AutoPostBack="True" OnTextChanged="txtSearchText_TextChanged"></asp:TextBox>
</span>
</p>
<p>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></p>
<p>
<asp:Label ID="lblNoResultsMessage" runat="server" Text="No results found" Visible="false"></asp:Label></p>
<p>
<asp:GridView ID="gvGlobalRoles" runat="server" AutoGenerateColumns="False" OnRowDeleting="gvGlobalRoles_RowDeleting" CssClass="zs-data-table">
<Columns>
<asp:BoundField DataField="Serial" HeaderText="Sr. No." />
<asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" />
<asp:BoundField DataField="RoleName" HeaderText="Role" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<span class="zs-icon zs-icon-delete"></span>
<asp:LinkButton Text="Delete" CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</p>
<asp:Panel ID="pnlOverlay" CssClass="zs-overlay" Visible="false" runat="server"></asp:Panel>
<asp:Panel ID="pnlModal" Visible="false" CssClass="zs-modal" Style="display: inline-block; position: fixed; top: 50%; left: 50%; margin-top: 0px; margin-left: 0px; transform: translate(-50%, -50%);" runat="server">
<header>
<span><% =ModalTitle %></span>
<asp:LinkButton ID="lbCloseModal" runat="server" CssClass="zs-icon zs-icon-close zs-icon-large" OnClick="lbCloseModal_Click"></asp:LinkButton>
</header>
<section>
<p>
<asp:Label ID="lblModalMessage" runat="server" Text=""></asp:Label></p>
<asp:Panel ID="pnlDeleteListItem" runat="server" Visible="false">
You have selected to delete a role. Press OK to continue or Cancel to abort.
</asp:Panel>
<asp:Panel ID="pnlAddEditListItem" runat="server" Visible="false">
<p>
<asp:Label ID="lblEmployeeToAdd" runat="server" Text="Employee Email"></asp:Label><br />
<asp:TextBox ID="txtEmployeeToAdd" runat="server" CssClass="zs-input"></asp:TextBox>
</p>
<p>
<asp:Label ID="lblRoleToAdd" runat="server" Text="Role"></asp:Label><br />
<asp:DropDownList ID="ddlRoleToAdd" runat="server" CssClass="zs-input"></asp:DropDownList>
</p>
</asp:Panel>
</section>
<footer>
<asp:LinkButton ID="lbCancelModal" runat="server" OnClick="lbCancelModal_Click">Cancel</asp:LinkButton>
<asp:Button ID="btnAddGlobalRoles" runat="server" Text="Add" CssClass="zs-button zs-button-action" OnClick="btnAddGlobalRoles_Click" OnClientClick="return IncreasePostBackControlValue();" Visible="false" />
<asp:Button ID="btnDeleteGlobalRole" runat="server" CssClass="zs-button zs-button-action" Text="OK" OnClick="btnDeleteGlobalRole_Click" OnClientClick="return IncreasePostBackControlValue();" Visible="false" />
</footer>
</asp:Panel>
<asp:HiddenField ID="hfPostBackControl" runat="server" ClientIDMode="Static" />
<script>
//$(document).on("click", "button,input[type='submit'],input[type='button']", function () {
// $("#hfPostBackControl").val($("#hfPostBackControl").val() == "" ? 1 : Number($("#hfPostBackControl").val()) + 1);
//});
function IncreasePostBackControlValue() {
$("#hfPostBackControl").val($("#hfPostBackControl").val() == "" ? 1 : Number($("#hfPostBackControl").val()) + 1);
return true;
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</section>
</asp:Content>
aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using OPT.Models;
namespace OPT
{
public partial class GlobalRoles : System.Web.UI.Page
{
BAL bal = new BAL();
string message = "";
int messageStateID;
DataTable dtRoles;
DataTable dtGlobalEmployeeRoles;
GlobalRole globalRoleToDelete;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadRoleDropDown();
LoadGlobalRolesFromDatabase();
Session["sPostBackValue"] = 0;
}
Generic.HideControls(AllMessageControls);
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CurrentPage"] = ePage.GlobalRoles;
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (!Pages.ShowGlobalRoles())
{
Generic.RediretToMesagePage("Unauthorized user");
}
if (gvGlobalRoles.Rows.Count > 0)
{
gvGlobalRoles.HeaderRow.TableSection = TableRowSection.TableHeader;
lblNoResultsMessage.Visible = false;
}
else
{
lblNoResultsMessage.Visible = true;
}
}
void LoadGlobalRolesFromDatabase()
{
dtGlobalEmployeeRoles = bal.GetGlobalEmployeeRoles(txtSearchText.Text, ref message, ref messageStateID);
Session["GlobalEmployeeRoles"] = dtGlobalEmployeeRoles;
gvGlobalRoles.DataSource = Session["GlobalEmployeeRoles"] as DataTable;
gvGlobalRoles.DataBind();
}
void LoadRoleDropDown()
{
dtRoles = bal.GetGlobalRoles(ref message, ref messageStateID);
Generic.PopulateDataTableInDropDown(ddlRoleToAdd, dtRoles, "ID", "Name", "Please select");
}
protected void gvGlobalRoles_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rowIndex = e.RowIndex;
globalRoleToDelete = new GlobalRole();
dtGlobalEmployeeRoles = Session["GlobalEmployeeRoles"] as DataTable;
globalRoleToDelete.ID = Convert.ToInt32(dtGlobalEmployeeRoles.Rows[rowIndex]["ID"].ToString());
Session["CurrentGlobalRole"] = globalRoleToDelete;
ModalTitle = "Delete Role";
Generic.ShowControls(modalDeleteControls);
}
protected void btnAddGlobalRoles_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
Employee employee = new Employee();
Role role = new Role();
employee.EmailID = txtEmployeeToAdd.Text;
role.ID = Convert.ToInt32(ddlRoleToAdd.SelectedValue);
bal.CreateGlobalEmployeeRole(employee, role, ref message, ref messageStateID);
if (messageStateID == 1)
{
Generic.HideControls(modalAllControls);
Generic.ShowMessage(lblMessage, message, messageStateID);
}
else
{
ModalTitle = eModalTitle.EditProject;
Generic.ShowMessage(lblModalMessage, message, messageStateID);
}
LoadGlobalRolesFromDatabase();
}
protected void btnDeleteGlobalRole_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
globalRoleToDelete = Session["CurrentGlobalRole"] as GlobalRole;
bal.DeleteGlobalEmployeeRole(globalRoleToDelete, ref message, ref messageStateID);
if (messageStateID == 1)
{
Generic.HideControls(modalAllControls);
Generic.ShowMessage(lblMessage, message, messageStateID);
}
else
{
ModalTitle = eModalTitle.EditProject;
Generic.ShowMessage(lblModalMessage, message, messageStateID);
}
LoadGlobalRolesFromDatabase();
Generic.HideControls(modalDeleteControls);
}
protected void lbCloseModal_Click(object sender, EventArgs e)
{
Generic.HideControls(modalAllControls);
}
protected void lbCancelModal_Click(object sender, EventArgs e)
{
Generic.HideControls(modalAllControls);
}
protected void btnOpenAddRoleModal_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
ModalTitle = "Add Role";
Generic.ClearControlValuesInContainer(pnlAddEditListItem);
Generic.ShowControls(modalAddControls);
}
protected void txtSearchText_TextChanged(object sender, EventArgs e)
{
LoadGlobalRolesFromDatabase();
}
private string _ModalTitle;
public string ModalTitle
{
get { return _ModalTitle; }
set { _ModalTitle = value; }
}
protected List<Control> modalAllControls
{
get
{
List<Control> controls = new List<Control>();
controls.AddRange(modalGenericControls);
controls.AddRange(modalAddControls);
controls.AddRange(modalDeleteControls);
return controls;
}
}
protected List<Control> modalGenericControls
{
get
{
return new List<Control>{
pnlOverlay as Control,
pnlModal as Control
};
}
}
protected List<Control> modalDeleteControls
{
get
{
List<Control> controls = new List<Control>{
pnlDeleteListItem as Control,
btnDeleteGlobalRole as Control
};
controls.AddRange(this.modalGenericControls);
return controls;
}
}
protected List<Control> modalAddControls
{
get
{
List<Control> controls = new List<Control>{
pnlAddEditListItem as Control,
btnAddGlobalRoles as Control
};
controls.AddRange(this.modalGenericControls);
return controls;
}
}
protected List<Control> AllMessageControls
{
get
{
List<Control> messageControls = new List<Control>{
lblMessage as Control,
lblModalMessage as Control
};
return messageControls;
}
}
}
}
Few supporting methods here
public static bool IsRefresh(HiddenField hfPostBackControl)
{
int sPostBackValue = HttpContext.Current.Session["sPostBackValue"] == null ? 0 : Convert.ToInt32(HttpContext.Current.Session["sPostBackValue"]);
int hPostBackValue = string.IsNullOrEmpty(hfPostBackControl.Value) ? 0 : Convert.ToInt32(hfPostBackControl.Value);
HttpContext.Current.Session["sPostBackValue"] = hPostBackValue;
return sPostBackValue == hPostBackValue;
}
/// <summary>
/// This method can be used for displaying pop ups after any action. One needs to pass the controls as parameter that need to shown on any event.
/// </summary>
/// <param name="controls">List of controls that need to be displyed as pop-up</param>
public static void ShowControls(List<Control> controls)
{
foreach (Control c in controls)
{
c.Visible = true;
}
}
/// <summary>
/// This method can be used for hiding pop ups being displayed. One needs to pass the controls as parameter that need to hidden on any event.
/// </summary>
/// <param name="controls">List of controls that need to be hidden</param>
public static void HideControls(List<Control> controls)
{
foreach (Control c in controls)
{
c.Visible = false;
}
}
public static void ShowMessage(Label lblMessage, string message, int messageStateID)
{
lblMessage.Text = message;
lblMessage.CssClass = messageStateID == 1 ? "zs-message zs-success" : "zs-message zs-error";
lblMessage.Visible = true;
}

Why DetailsView.ChangeMode method does not fire ModeChanging and ModeChanged events?

I have an ASP.NET WebApplication page with DetailsView bounded to SqlDataSource.
When I try to change mode by auto-generated Edit or Insert buttons, events are fired.
When I try to change mode programmatically by DetailsView.ChangeMode method call (inside custom button click), ModeChanging and ModeChanged events are not fired.
Why it does not work ?
There is aspx listing:
<form id="form1" runat="server">
<div>
<h1><asp:Label ID="Label" runat="server" Text="ReadOnly" /></h1>
<asp:DetailsView ID="DetailsView" runat="server"
DataSourceID="SqlDataSource"
EnableModelValidation="True"
AllowPaging="True"
AutoGenerateEditButton="True"
AutoGenerateInsertButton="True"
OnModeChanged="DetailsView_ModeChanged">
<FooterTemplate>
</FooterTemplate>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:PEMDConnectionString %>"
SelectCommand="SELECT * FROM [evd].[WaterTemplates]"
InsertCommand="INSERT INTO [evd].[WaterTemplates] (TemplateName,TemplateDescription) VALUES (#Name,#Description)" />
<asp:Button ID="InsertByChangeModeButton" runat="server"
OnClick="InsertByChangeModeButton_Click"
Text="Insert By ChangeMode" />
<asp:Button ID="EditByChangeModeButton" runat="server"
OnClick="EditByChangeModeButton_Click"
Text="Edit By ChangeMode" />
</div>
</form>
and here is code behind:
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
switch (DetailsView.CurrentMode)
{
case DetailsViewMode.Edit:
case DetailsViewMode.Insert:
EditByChangeModeButton.Visible = false;
InsertByChangeModeButton.Visible = false;
break;
case DetailsViewMode.ReadOnly:
InsertByChangeModeButton.Visible = true;
EditByChangeModeButton.Visible = true;
break;
default:
break;
}
}
protected void InsertByChangeModeButton_Click(object sender, EventArgs e)
{
DetailsView.ChangeMode(DetailsViewMode.Insert);
}
protected void EditByChangeModeButton_Click(object sender, EventArgs e)
{
DetailsView.ChangeMode(DetailsViewMode.Edit);
}
protected void DetailsView_ModeChanged(object sender, EventArgs e)
{
switch (DetailsView.CurrentMode)
{
case DetailsViewMode.Edit:
Label.Text = "Edit";
break;
case DetailsViewMode.Insert:
Label.Text = "Insert";
break;
case DetailsViewMode.ReadOnly:
Label.Text = "ReadOnly";
break;
default:
break;
}
}
}
}

ASP.NET: Ajax UpdatePanel issue

I am supposed to update the progress & display the corresponding message on the client side while the function is still under execution at server side.
How can I achieve this?
The function looks like:
protected void Button1_Click(object sender, EventArgs e)
{
string Result = "Success";
if (Result == "Success")
{
Label1.Text = "Plan mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Packing date mst Started";
}
if (Result == "Success")
{
Label1.Text = "Packing date mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Etd mst Started";
}
if (Result == "Success")
{
Label1.Text = "Etd mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Inner box mst Started";
}
}
And I have to update the text of Label1 while the above function is still under execution.
I have tried using AJAX (although I'm still a beginner), but with no success. Here's what I did:
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="10" ontick="Timer1_Tick1">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
And the corresponding events:
protected void Page_Load(object sender, EventArgs e)
{
UpdatePanel1.UpdateMode = UpdatePanelUpdateMode.Conditional;
}
protected void Timer1_Tick1(object sender, EventArgs e)
{
UpdatePanel1.Update();
}
Any other alternatives other than AJAX such as via jQuery or otherwise are also welcome.
these might help you:
http://forums.asp.net/t/1500201.aspx
ASP.NET Asynchronous label update

How to close radwindow manager form server side button click

Hi all I have designed a radwindow manager which will have a dropdown and a textbox and a button which are placed inside a update panel.
Every thing works fine but on button click I am closing my window manager as follows
RadWindowManager1.Windows[0].VisibleOnPageLoad = false;
But this didn't work can some one help me this is my design and code
<telerik:RadWindowManager ID="RadWindowManager1" runat="server" Behavior="Default"
InitialBehavior="None">
<Windows>
<telerik:RadWindow ID="RadWindow1" runat="server" Behaviors="Default" InitialBehaviors="None"
OpenerElementID="btn" Width="650" Height="480" VisibleOnPageLoad="false">
<ContentTemplate>
<asp:UpdatePanel ID="up" runat="server" OnUnload="up_Unload">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdcmb" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="radbtn" EventName="Click" />
</Triggers>
<ContentTemplate>
<telerik:RadComboBox ID="rdcmb" runat="server" AutoPostBack="true" OnSelectedIndexChanged="sel">
<Items>
<telerik:RadComboBoxItem Text="One" Value="One" />
<telerik:RadComboBoxItem Text="Two" Value="Two" />
<telerik:RadComboBoxItem Text="Three" Value="Three" />
<telerik:RadComboBoxItem Text="Four" Value="Four" />
</Items>
</telerik:RadComboBox>
<telerik:RadTextBox ID="rdText" runat="server">
</telerik:RadTextBox>
<telerik:RadButton ID="radbtn" runat="server" Text="Save" OnClick="btn_Click">
</telerik:RadButton>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
<telerik:RadButton ID="rdbtnwhAnother" Text="Add WithHolding" runat="server" ButtonType="LinkButton"
OnClick="rdbtnwhAnother_Click">
</telerik:RadButton>
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RadWindowManager1.Windows[0].VisibleOnPageLoad = false;
}
}
protected void rdbtnwhAnother_Click(object sender, EventArgs e)
{
RadWindowManager1.Windows[0].VisibleOnPageLoad = true;
}
protected void btn_Click(object sender, EventArgs e)
{
RadWindowManager1.Windows[0].VisibleOnPageLoad = false;
}
protected void sel(object sender, EventArgs e)
{
rdText.Text = rdcmb.SelectedItem.Text;
}
protected void up_Unload(object sender, EventArgs e)
{
/* Cast sender as an updatePanel, and use reflection to invoke * * the page's scriptmanger registerUpdatePanel() method * * */
//RadWindowManager1.Windows[0].VisibleOnPageLoad = false;
UpdatePanel aUpdatePanel = sender as UpdatePanel;
MethodInfo m = (
from methods in typeof(ScriptManager).GetMethods(
BindingFlags.NonPublic | BindingFlags.Instance
)
where methods.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")
select methods).First<MethodInfo>();
m.Invoke(ScriptManager.GetCurrent(aUpdatePanel.Page), new object[] { aUpdatePanel });
}
<script type="text/javascript">
function getRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function clientClose(arg) {
getRadWindow().close(arg);
}
</script>
<telerik:RadButton ID="radbtn" runat="server" Text="Save" OnClick="btn_Click">
</telerik:RadButton>
protected void btn_Click(object sender, EventArgs e)
{
string script = "clientClose('');";
ScriptManager.RegisterStartupScript(Page, typeof(Page),
"closeScript", script, true);
}

GridView event raise unexpectedly after postback

Consider this Asp.net page code:
<head runat="server">
<title></title>
<script type="text/javascript">
function showhide(master, detail) {
var src = $(master).children()[0].src;
if (src.endsWith("plus.png"))
src = src.replace('plus.png', 'minus.png');
else
src = src.replace('minus.png', 'plus.png');
$(master).children()[0].src = src;
$(detail).slideToggle("normal");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/scripts/jquery-1.6.2.min.js" ScriptMode="Release" />
</Scripts>
</asp:ScriptManager>
<div>
<asp:SqlDataSource ID="sqlDsCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders
FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID]
Group By [Customers].[CustomerID], [Customers].[CompanyName]">
</asp:SqlDataSource>
<asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="group" id='<%#String.Format("customer{0}",Container.DataItemIndex) %>'
onclick='showhide(<%#String.Format("\"#customer{0}\"",Container.DataItemIndex) %>,<%#String.Format("\"#order{0}\"",Container.DataItemIndex) %>)'>
<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
Style="margin-right: 5px;" runat="server" /><span class="header">
<%#Eval("CustomerID")%>
:
<%#Eval("CompanyName")%>
(<%#Eval("TotalOrders")%>Orders) </span>
</div>
<div id='<%#String.Format("order{0}",Container.DataItemIndex) %>' class="order">
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="ddd" runat="server"
ShowHeader="true" EnableViewState="false">
<RowStyle CssClass="row" />
<AlternatingRowStyle CssClass="altrow" />
<Columns>
<asp:TemplateField ItemStyle-CssClass="rownum">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order ID" DataField="OrderID" ItemStyle-Width="80px" />
<asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
<asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="110px" />
<asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}"
ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
and the code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string custID = ((DataRowView)e.Row.DataItem)["CustomerID"].ToString();
using (DataClassesDataContext dc=new DataClassesDataContext())
{
List<Order> ord = (from o in dc.Orders
where o.CustomerID == custID.Trim()
select o).ToList();
GridView ctrl = e.Row.FindControl("ddd") as GridView;
ctrl.DataSource = ord;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
the problem is when I Click on Button1 to redirect to another page gvCustomers_RowCreated raise and I get Null reference error.Why this event raised after postback?
EDIT 1):
I removed SqlDataSource and bind GridView in the code behind like this:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (DataClassesDataContext dc=new DataClassesDataContext())
{
var query = dc.ExecuteQuery<clsRetern>("SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID] Group By [Customers].[CustomerID], [Customers].[CompanyName]").ToList();
List<clsRetern> ret = new List<clsRetern>();
foreach (var item in query)
{
clsRetern r = new clsRetern();
r.CompanyName = item.CompanyName;
r.CustomerID = item.CustomerID;
r.TotalOrders = item.TotalOrders;
ret.Add(r);
}
gvCustomers.DataSource = ret;
gvCustomers.DataBind();
}
}
}
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string custID = ((clsRetern)e.Row.DataItem).CustomerID.Trim();
using (DataClassesDataContext dc=new DataClassesDataContext())
{
List<Order> ord = (from o in dc.Orders
where o.CustomerID == custID.Trim()
select o).ToList();
GridView ctrl = e.Row.FindControl("ddd") as GridView;
ctrl.DataSource = ord;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx",true);
}
}
public class clsRetern
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public int TotalOrders { get; set; }
}
I tried Response.Redirect("Default.aspx"); but the problem still remains.
If you understand ASP.NET page model then this question should not come to you. Every time request goes to ASP.NET page, a new page object is created along with entire control tree and the state is managed using view-state in post-back scenarios. So in your case, whenever post-back happens, a new page and grid-view is created. The data for the gid-view would be persisted in thew view-state and grid would be bound to that data.
The RowCreated event is raised whenever grid row is created regardless of whether DataBind is explicitly called or not. The intent of the event is so that one can tweak with UI (grid-view cells) - e.g. some controls can be pushed into grid-view cells if required. The same should happen regardless of post-back scenario other wise those dynamic controls will not get created. Typically, these controls will restore their state using view-state and your get your grid-view UI (control tree) back as it was in first page cycle.
Thats because even if you fire Response.Redirect, the Page_Load event would still be raised and if your GridView binding code is not inside !IsPostBack, that code will be hit.
Try this.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
//bind gridview here
}
}
catch (Exception exception)
{
//Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
}
Savvy?
Add EnableViewState=False to the page directive to prevent "RowCreated" running on every post back.

Resources