modalpopupextender with dropdownlist and update panel issue - asp.net

I have asp:DetailsView in popup (I use modalpopupextender) and I have dropdownlist inside detailsview with autopostback. DetailView is inside updatepanel. But when I change value of dropdownlist the PageLoad function is called anyway, and dropdown index changes to 0.
<asp:Button ID="FakeClickButton5" runat="server" Text="FakeButton" CssClass="hideButton" />
<asp:Panel ID="PopupPanelDetail" runat="server" CssClass="modalPopup" >
<asp:Panel ID="Panel6" runat="server" >
<asp:UpdatePanel ID="uptblTest" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:DetailsView ID="DetailsViewMain" runat="server" AutoGenerateRows="false"
DataKeyNames="Id" DataSourceID="ObjectDataSourceDetailMain" Height="50px"
onitemcommand="DetailsViewMain_ItemCommand"
oniteminserted="DetailsViewMain_ItemInserted"
Width="250px" >
<Fields>
<asp:BoundField DataField="Id" HeaderText="Id"
InsertVisible="False" ReadOnly="True" SortExpression="Id"
Visible="False" />
<asp:BoundField DataField="name" HeaderText="name"
SortExpression="name" />
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:DropDownList ID="ddType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddType_OnSelectedIndexChanged" onload="ddType_Load">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowInsertButton="True"
Visible="False" />
</Fields>
<HeaderStyle CssClass="bold" HorizontalAlign="Center"></HeaderStyle>
</asp:DetailsView>
<asp:Panel ID="Panel7" runat="server">
<asp:LinkButton ID="SaveDetailLinkButton" runat="server" CausesValidation="True"
onclick="SaveDetailLinkButton_Click" SkinID="blackButton" ValidationGroup="ServiceValidation">Save</asp:LinkButton>
<asp:LinkButton ID="CancelDetailLinkButton3" runat="server"
onclick="CancelDetailLinkButton3_Click" SkinID="blackButton">Cancel</asp:LinkButton>
</asp:Panel>
<asp:ObjectDataSource ID="ObjectDataSourceDetailMain" runat="server"
InsertMethod="InsertParam"
SelectMethod="GetParamByID"
UpdateMethod="UpdateParam"
TypeName="DatasorceMatch"
DataObjectTypeName="ParamCustom"
OldValuesParameterFormatString="original_{0}"
oninserting="ObjectDataSourceDetailMain_Inserting" >
<SelectParameters>
<asp:ControlParameter ControlID="GridViewParams" Name="Id"
PropertyName="SelectedDataKey.Value" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</asp:Panel>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderDetails" runat="server"
PopupControlID="PopupPanelDetail" TargetControlID="FakeClickButton2"
BackgroundCssClass="modalBackground" />
actually it's strange that dropdownlist reloaded because update panel mode is conditional and I don't update it in code.
Here is my server code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DetailsViewMain_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Cancel")
{
DetailsViewMain.Visible = false;
}
}
protected void DetailsViewMain_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
GridViewParams.DataBind();
DetailsViewMain.Visible = false;
}
protected void SaveDetailLinkButton_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
GridViewParams.SelectedIndex = -1;
if (DetailsViewMain.CurrentMode == DetailsViewMode.Edit)
{
DetailsViewMain.UpdateItem(true);
}
if (DetailsViewMain.CurrentMode == DetailsViewMode.Insert)
{
DetailsViewMain.InsertItem(true);
}
ModalPopupExtenderDetails.Hide();
GridViewParams.DataBind();
}
else
{
ModalPopupExtenderDetails.Show();
}
}
protected void CancelDetailLinkButton3_Click(object sender, EventArgs e)
{
ModalPopupExtenderDetails.Hide();
GridViewParams.SelectedIndex = -1;
GridViewParams.DataBind();
}
protected void ObjectDataSourceDetailMain_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
//int selectedID_ofType = (int)ViewState[viewState_typeID];
int selectedID_ofType = int.Parse(dropDownList_ddType.SelectedValue);
((ParamCustom)e.InputParameters[0]).typeID = selectedID_ofType;
}
protected void ddType_Load(object sender, EventArgs e)
{
dropDownList_ddType = (DropDownList)sender;
if (DetailsViewMain.CurrentMode == DetailsViewMode.Insert)
{
((DropDownList)sender).Items.Clear();
((DropDownList)sender).Items.Add(new ListItem(#"Choose", (0).ToString()));
foreach (ParamType paramType in DBHelper.sharedInstance().getAllParamTypes())
{
ListItem listItem = new ListItem(paramType.name, paramType.id.ToString());
((DropDownList)sender).Items.Add(listItem);
}
}
}
protected void ddType_OnSelectedIndexChanged(object sender, EventArgs e)
{
//int selectedID_ofType = int.Parse(((DropDownList)sender).SelectedValue);
//ViewState[viewState_typeID] = selectedID_ofType;
}
What I need is just to change values of dropdownlist without page reloading or without popup disappearing and save this value.

Related

get value from asp boundfield and store to sql database via button click?

i want to get this value from webform 1 (admin side) when button is clicked:
here is my full viewcreditrequest code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CssClass="table table-hover table-striped"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress"
SortExpression="EmailAddress" />
<asp:BoundField DataField="CompanyAddress" HeaderText="CompanyAddress"
SortExpression="CompanyAddress" />
<asp:BoundField DataField="IncomeRange" HeaderText="IncomeRange"
SortExpression="IncomeRange" />
<asp:BoundField DataField="CreditRequest" HeaderText="CreditRequest"
SortExpression="CreditRequest" />
<asp:BoundField DataField="ContactNumber" HeaderText="ContactNumber" SortExpression="ContactNumber" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Approve" CommandName="Approve" CommandArgument='<%# Eval("CreditRequest") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IslandGasAdminFM"] != null)
{
bindgrid();
Label1.Text = "- Finance Manager";
}
else
{
Response.Write("<script>alert('Finance Manager credentials needed'); window.location.href='LogIn.aspx';</script>");
}
}
public void bindgrid()
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand("select * from CreditRequests ", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select * from CreditRequests", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
and pass it on to webform 2 (client side):
<asp:TextBox ID="txtCredit" runat="server"></asp:TextBox>
this is what i got so far:
admin side:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnApprove" runat="server" Text="Approve" OnClick ="btnApprove_Click" />
</ItemTemplate>
</asp:TemplateField>
code behind:
protected void btnApprove_Click(object sender, EventArgs e)
{
//code for getting the boundfield "creditrequest" and if possible, store it in database for future use.
}
is there any way to get the creditrequest value from boundfield and store it in database?
Here you can do two thing's 1.since you are using Button, add a new row in gridview like this
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button CommandArgument='<%#Eval("CreditRequest") %>' runat="server" Text="View" ID="btnEdit" OnClick="btnEdit_OnClick"/>
</ItemTemplate>
</asp:TemplateField>
and the code behind is like this
protected void btnEdit_OnClick(object sender, EventArgs e)
{
if (sender != null)
{
string id = ((Button)sender).CommandArgument.ToString();
Response.Redirect("yourpagename.aspx?value=" + id);
}
}
and on another page Client side get the query string value like this
string value = Request.QueryString["value"])
And 2nd and easy method will be to use hyperlink instead of button like this
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("CreditRequest", "~/yourpagename.aspx?value={0}") %>' Text="Edit" "></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Copy the code below EXACTLY as I'm showing and it will work. I've just tested on my computer:
.ASPX:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="CreditRequest" HeaderText="Credit Request" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Approve" CommandName="Approve" CommandArgument='<%# Eval("CreditRequest") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
public partial class delete_me : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)//THIS IS IMPORTANT.GridView1_RowCommand will not fire unless you add this line
{
var p1 = new Person() { Name = "Person 1",CreditRequest="Credit Request 1" };
var p2 = new Person() { Name = "Person 2",CreditRequest="Credit Request 2" };
var list = new List<Person> { p1, p2 };
GridView1.DataSource = list;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
System.Diagnostics.Debugger.Break();
if(e.CommandName == "Approve")
{
string creditRequest = e.CommandArgument as string;
}
}
}
public class Person
{
public string Name { get; set; }
public string CreditRequest { get; set; }
}

Multiple delete rows in radgrid

My problem :
I want to delete all selected records using checkbox in RadGrid..
How to write the code for this..
I have a code for simple GridView But its not working in RadGrid.
Please try with below code snippet.
Method1
.aspx
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView DataKeyNames="ID">
<Columns>
<telerik:GridBoundColumn DataField="Name" UniqueName="Name" HeaderText="Name">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
CheckBox CheckBox1 = item.FindControl("CheckBox1") as CheckBox;
if (CheckBox1 != null && CheckBox1.Checked)
{
// Access data key
string strID = item.GetDataKeyValue("ID").ToString();
// Access column
string strName = item["Name"].Text; // "Name" is column unique name
// delete logic comes here
}
}
}
Method2
.aspx
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False"
OnNeedDataSource="RadGrid1_NeedDataSource"
AllowMultiRowSelection="true">
<MasterTableView DataKeyNames="ID">
<Columns>
<telerik:GridClientSelectColumn>
</telerik:GridClientSelectColumn>
<telerik:GridBoundColumn DataField="Name" UniqueName="Name" HeaderText="Name">
</telerik:GridBoundColumn>
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
</Columns>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="true" />
</ClientSettings>
</telerik:RadGrid>
.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGrid1.SelectedItems)
{
if (item.Selected)
{
// Access data key
string strID = item.GetDataKeyValue("ID").ToString();
// Access column
string strName = item["Name"].Text; // "Name" is column unique name
// delete logic comes here
}
}
}
Common code for both of above method.
.aspx
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
.aspx.cs
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
dynamic data = new[] {
new { ID = 1, Name ="Name1",path="1.jpg"},
new { ID = 2, Name = "Name2",path="2.jpg"},
new { ID = 3, Name = "Name3",path="3.jpg"},
new { ID = 4, Name = "Name4",path="2.jpg"},
new { ID = 5, Name = "Name5",path="3.jpg"}
};
RadGrid1.DataSource = data;
}

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.

After applying a filter to linqdatasource connected to GridView ,clicking edit bring me back to the old data

Like once said a picture worth one thousand word
when I press the edit button I go back to the old data, with first row in the edit mode
like the following
this is the code I use when searching with student name , or date ....
LinqDataSource1.Where = "pay_date.Contains(" +
(Convert.ToString(Convert.ToDateTime(TextBox1.Text))) + ")";
I tried to use AJAX , didn't work
I found in the linqdatasource a property called linqdatasource storeoriginalvaluesinviewstate
I made it false but go the same problem ,
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="EDPayment.ascx.cs" Inherits="Admin_ED_EDPayment" %>
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="~/Admin/ED/Student_AutoComplete.asmx" />
</Services>
</asp:ScriptManagerProxy>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Label ID="Label3" runat="server"
Text="Search By Student Name:"></asp:Label>
<asp:TextBox runat="server" ID="myTextBox" Width="300" ontextchanged="myTextBox_TextChanged" />
<asp:autocompleteextender
runat="server"
ID="autoComplete1"
TargetControlID="myTextBox"
ServicePath="~/Admin/ED/Student_AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="12" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Search" />
<br />
<br />
<asp:Label ID="Label4" runat="server" Text="Search By Date:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server"
BehaviorID="TextBox1_CalendarExtender" Enabled="True"
TargetControlID="TextBox1">
</asp:CalendarExtender>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Search" />
<br />
<br />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click"
Text="Search By Date & Name" />
<br />
<asp:Label ID="Label5" runat="server"></asp:Label>
<br />
<asp:Button ID="Button4" runat="server" onclick="Button4_Click"
Text="Show All Payments" /></div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="pay_id"
DataSourceID="LinqDataSource1" onrowediting="GridView1_RowEditing">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="pay_id" HeaderText="pay_id" InsertVisible="False"
ReadOnly="True" SortExpression="pay_id" />
<asp:BoundField DataField="pay_amount" HeaderText="pay_amount"
SortExpression="pay_amount" />
<asp:BoundField DataField="pay_date" HeaderText="pay_date"
SortExpression="pay_date" />
<asp:TemplateField HeaderText="pay_st_id" SortExpression="pay_st_id">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="LinqDataSource2" DataTextField="st_fullname"
DataValueField="st_id" SelectedValue='<%# Bind("pay_st_id") %>'>
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="TeacherAssistantDataContext"
OrderBy="st_fname, st_mname, st_lname" Select="new (st_fullname, st_id)"
TableName="students">
</asp:LinqDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("pay_st_id") %>'
Visible="False"></asp:Label>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="LinqDataSource3" DataTextField="st_fullname"
DataValueField="st_id" Enabled="False">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource3" runat="server"
ContextTypeName="TeacherAssistantDataContext"
OrderBy="st_fname, st_mname, st_lname" Select="new (st_id, st_fullname)"
TableName="students" Where="st_id == #st_id">
<WhereParameters>
<asp:ControlParameter ControlID="Label1" Name="st_id" PropertyName="Text"
Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="TeacherAssistantDataContext" EnableDelete="True"
EnableUpdate="True" OrderBy="pay_date, pay_amount, pay_st_id"
TableName="payments">
</asp:LinqDataSource>
</ContentTemplate>
</asp:UpdatePanel>
.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Admin_ED_EDPayment : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
go1();
}
protected void go1()
{
int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
LinqDataSource1.Where = "pay_st_id == " + id[0].ToString();
// Parameter p = new Parameter("", System.Data.DbType.Int32, id[0].ToString());
//LinqDataSource1.WhereParameters.Add(p);
// LinqDataSource1.DataBind();
//fix();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
go2();
}
protected void go2()
{
LinqDataSource1.Where = "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";
fix();
}
void fix()
{
// LinqDataSource1.
}
protected void Button3_Click(object sender, EventArgs e)
{
int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
LinqDataSource1.Where = "pay_st_id == " + id[0].ToString() + " AND " + "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";
}
protected void myTextBox_TextChanged(object sender, EventArgs e)
{
go1();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
go2();
}
protected void Button4_Click(object sender, EventArgs e)
{
LinqDataSource1.TableName = "payments";
LinqDataSource1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
}
I think you have to put your code in the page load and not in the button click and then you check first if the textbox contains data and if it contains data, apply your filter.
I think your problem is because when the page loads for the second time, the datagrid datbind function get called which gets all the data again.
try this update
<asp:LinqDataSource ID="LinqDataSource3" runat="server"
ContextTypeName="TeacherAssistantDataContext" OnSelected="LinqDataSource1_Selected"
OrderBy="st_fname, st_mname, st_lname" Select="new (st_id, st_fullname)"
TableName="students" Where="st_id == #st_id">
<WhereParameters>
<asp:ControlParameter ControlID="Label1" Name="st_id" PropertyName="Text"
Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
Code behind:
protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
if(!string.IsNullOrEmpty( myTextBox.Text))
{
go1();
}
if(!string.IsNullOrEmpty( TextBox1.Text))
{
go2();
}
}
I found a solution based on this topic : How can I prevent the LinqDataSource Where clause from resetting on postback? :Source
All I needed is to save the where clause of the linqdatasource and reload it again in the page_load event the final code become
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Admin_ED_EDPayment : System.Web.UI.UserControl
{
//private Boolean b1 = false, b2 = false, b3 = false;
public string MyLinqSourceWhere
{
get { return (string)this.ViewState["MyLinqSourceWhere"]; }
set { this.ViewState["MyLinqSourceWhere"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
this.LinqDataSource1.Where = this.MyLinqSourceWhere;
}
protected void Button1_Click(object sender, EventArgs e)
{
go1();
}
protected void go1()
{
int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
this.MyLinqSourceWhere = "pay_st_id == " + id[0].ToString();
this.LinqDataSource1.Where = this.MyLinqSourceWhere;
}
protected void go3()
{
int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
this.MyLinqSourceWhere = "pay_st_id == " + id[0].ToString() + " AND " + "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";
this.LinqDataSource1.Where = this.MyLinqSourceWhere;
}
protected void Button2_Click(object sender, EventArgs e)
{
go2();
}
protected void go2()
{
this.MyLinqSourceWhere = "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";
this.LinqDataSource1.Where = this.MyLinqSourceWhere;
}
protected void Button3_Click(object sender, EventArgs e)
{
go3();
}
protected void myTextBox_TextChanged(object sender, EventArgs e)
{
go1();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
go2();
}
protected void Button4_Click(object sender, EventArgs e)
{
LinqDataSource1.TableName = "payments";
LinqDataSource1.DataBind();
}
}

Resources