OnCheckedChanged event not firing - c#

I have a GridView with a column of checkboxes (the rest of the GridView is being populated from a database). I'm using AJAX to perform different functions, and I'm wondering if i'm just not calling the OnCheckedChanged event in the right place. Should it be wrapped in some sort of UpdatePanel? I'm still really new to how all of this works...basically what I'm aiming for is to change a bit value in my database when a checkbox is checked. I know the logic of how to do that, I just don't know if I'm addressing my OnCheckedChanged event the right way.
.CS
protected void CheckBoxProcess_OnCheckedChanged(Object sender, EventArgs args)
{
CheckBox checkbox = (CheckBox)sender;
GridViewRow row = (GridViewRow)checkbox.NamingContainer;
OrderBrowser.Text += "CHANGED";
}
}
.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "orderByList"
EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlId="searchButton" EventName="Click" />
</Triggers>
<ContentTemplate>
<div align="center">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "fName"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true"
selectedindex="0">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" runat="server" Enabled="true" OnCheckedChanged = "CheckBoxProcess_OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:TextBox ID="OrderBrowser" columns="100" Rows="14" runat="server" Wrap="false" TextMode="MultiLine" ReadOnly = "true">
</asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>

Try turning AutoPostBack on for the checkbox control.
<asp:CheckBox ID="CheckBoxProcess" runat="server" Enabled="true" OnCheckedChanged = "CheckBoxProcess_OnCheckedChanged" AutoPostBack="true" />
This maybe the reason your method isn't being called.

Please try to check the value with the DB:
Checked='<%# Convert.ToBoolean(Eval("Processed")) %>'

Related

Create controls dynamically on button click

I am trying to create dynamic controls on button click.
HTML:
<asp:LinkButton ID="lnkSrt" runat="server" Text="Multi Sort" ForeColor="Black" Font-Names="Calibri" Font-Size="10pt" />
<ajax:ModalPopupExtender runat="server" ID="mpeSrt"
TargetControlID="lnkSrt" PopupControlID="pnlSrt" CancelControlID="btnClose">
</ajax:ModalPopupExtender>
<asp:UpdatePanel ID="upPanel" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlSort" runat="server" align="center" Style="display: none" BackColor="LightGray">
<asp:Label runat="server" Text="Sort By Column" />
<asp:DropDownList ID="ddlColumnSort" runat="server" AutoPostBack="true" />
<asp:Label runat="server" Text="Order By" />
<asp:DropDownList ID="ddlOrder" runat="server" AutoPostBack="true">
<asp:ListItem Text="Ascending" Value="0"></asp:ListItem>
<asp:ListItem Text="Descending" Value="1"></asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="lnkAdd" runat="server" Text="Add Sorting" Font-Underline="true" OnClick="lnkAddOrder_Click" Font-Names="Calibri" Font-Size="10pt" ForeColor="Black" />
<asp:Button ID="btnSorting" runat="server" Text="Sort" OnClick="btnSorting_Click" />
<asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
CODE:
When clicked on AddSorting I am trying to create dropdown control using below code and the controls doesn't show.
protected void lnkAddSort_Click(object sender, EventArgs e)
{
int index = pnlSort.Controls.OfType<DropDownList>().ToList().Count + 1;
this.Createddl("ddldyn" + index);
}
public void Createddl(string id)
{
DropDownList ddl = new DropDownList();
ddl.ID = id;
pnlSort.Controls.Add(ddl);
Literal lt = new Literal();
lt.Text = "<br />";
pnlSort.Controls.Add(lt);
}
Image:
pnlSrt is set to display: none so the dynamically added child controls will not show either.
As per the #Yoshi answer. You could set visible true for the pnlSrt control by using pnlSort.Style["display"] = "block";// or pnlSort.Attributes.Add("style", "display:block");
Try this
public void Createddl(string id)
{
DropDownList ddl = new DropDownList();
ddl.ID = id;
pnlSort.Controls.Add(ddl);
Literal lt = new Literal();
lt.Text = "<br />";
pnlSort.Controls.Add(lt);
pnlSort.Attributes.Add("style", "display:block");
}

How to correctly get cell value in gridview after clicking on a linkbutton inside a gridview and enable correct async postback to display a modal

I am making a reservation system and currently stuck on the following situation.
Basically I have a GridView which is loaded with the reservation ID and two LinkButton which opens a modal popup to enable the customer to view the details.
What I want to achieve is that when I click any LinkButton, it will show the ID from the first cell of a GridViewRow.
I have tried these methods here, here, here, and here but it still doesn't work. Is there any way to do it, Aside from using a SELECT Command and does involve async postback or if async postback is not possible with this, any fix recommended?
Here is my GridView code:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvReservationSummaries"/>
</Triggers>
<ContentTemplate>
<h2>Reservations</h2>
<br />
<asp:GridView ID="gvReservationSummaries" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" ShowHeader="False" CellPadding="5" CellSpacing="5"
onrowcommand="Gridview1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%# Eval("Master_Reservation_ID")%></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReservationDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Reservation Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReceiptDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Receipt Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9E4ABD_GratchiOBRSConnectionString2 %>"
SelectCommand="SELECT [Master_Reservation_ID] FROM [Master_Reservation] WHERE User_Unique_ID = #uuid">
<SelectParameters>
<asp:SessionParameter Name="uuid" SessionField="uid" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Button ID="btnShowModal" runat="server" Text="Show Modal 1 (Debug Purposes Only)" onclick="btnShowModal_Click" />
<!--Here, put the details of the reservaton, plus options to edit reservation.-->
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<asp:Panel ID="reservationSummaryModal" runat="server" Width="500px" Height="500px" style="display: none; background-color:Black; color:#CCC;">
<asp:Button ID="btnExitRs" runat="server" Text="Hide Modal (Debug Purposes Only)" onclick="btnExitAct_Click" />
<asp:Label ID="lblReservationSummary" runat="server" Text="Label"></asp:Label>
</asp:Panel>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="HiddenField1" PopupControlID="reservationSummaryModal" BackgroundCssClass="modalBg" CancelControlID="btnExitRs">
</asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField1" runat="server" />
And here is my codebehind:
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ViewReservationDetails")
{
//GridViewRow gvr = gvReservationSummaries.Rows[Convert.ToInt32(e.CommandArgument)];
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else if (e.CommandName == "ViewReceiptDetails")
{
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else
{
}
}

ListView inside an UpdatePanel not getting rebound

I have a ASP.NET ListView inside an UpdatePanel.
In the ItemTemplate there are 2 buttons with Commands "UpdateCart" & "RemoveCart".
In both the commands, the datasource of ListView (an SQL DataSource) gets rebound.
There is no InsertCommand/UpdateCommand/DeleteCommand on the SqlDataSource
My problem is :
Whenver these buttons are clicked : the datasource does not get refreshed.
however I can see from debug mode that values are indeed passed to the datasource selecting method correctly.
The relevant ASPX Page :
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" DisplayAfter="10" runat="server" AssociatedUpdatePanelID="UpnlMain">
<ProgressTemplate>
<div class="divWaiting">
<asp:Label ID="lblWait" runat="server" Text=" Please wait... " />
<asp:Image ID="imgWait" runat="server" ImageAlign="Middle" ImageUrl="~/Image/AjaxLoading.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpnlMain" runat="server">
<ContentTemplate>
<asp:ListView ID="lvMain" runat="server" DataSourceID="sdsMain" DataKeyNames="Code"
OnItemCommand="lvMain_ItemCommand">
<EmptyDataTemplate>
<div class="col-xs-12">
<span>No Items in Cart.</span>
</div>
</EmptyDataTemplate>
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" Text='<%# Eval("Code") %>' Visible="false" />
Product " <asp:Literal ID="ltrStyleNo" runat="server" Text='<%# Eval("StyleNo") %>' />
Qty : <asp:TextBox ID="txtQty" runat="server" type="number" CssClass="txtQty OnlyNumeric form-control text-center input-sm"
Text='<%# Eval("Qty") %>'></asp:TextBox>
<asp:ImageButton ID="btnUpdate" runat="server" ImageUrl="~/image/update.png" CssClass="btn btnUpdateCart"
CommandName="UpdateCart" AlternateText="Update Qty" />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/image/delet.png" CssClass="btn"
CommandName="DeleteCart" AlternateText="Remove Item" />
</ItemTemplate>
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="sdsMain" runat="server" ConnectionString="<%$ ConnectionStrings:CurrentConnectionString %>"
SelectCommand="pGetItemsForCart" SelectCommandType="StoredProcedure" OnSelecting="sdsMain_Selecting"
UpdateCommand="NoUpdate" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter DefaultValue="-1" Name="WoSCodeCSV" Type="String" />
</UpdateParameters>
<SelectParameters>
<asp:Parameter DefaultValue="-1" Name="WoSCodeCSV" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The Code Behind Code :
protected void sdsMain_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters[0].Value = GetCartCodes(); //gives some values in csv from Session ..
}
protected void lvMain_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "UpdateCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
TextBox txtQty = e.Item.FindControl("txtQty") as TextBox;
//Some update in a Session
BindListView();
}
else if (e.CommandName.ToLower() == "DeleteCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
//Some update in a Session
BindListView();
}
else if (e.CommandName.ToLower() == "RefreshCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
BL.StyleSearchHelper.PriceItem(Page, lblCode.Text);
BindListView();
}
}
void BindListView()
{
sdsMain.DataBind();
lvMain.DataBind();
}
Try replace your buttons outside the updatepanel. Page will not getting refresh when the buttons are in updatepanel. sorry i can't make comment so I post here as an answer.

Autopostback is working only for the first time in ASP.NET?

Here i am using a radio button to calculate the date difference between two textboxes and i am showing it in another textbox.It is working only for the first time when i click the radio button after that it is not working..Here is my code
<asp:RadioButton ID="rdoSpecifiedDates" runat="server" class="bodycontent" GroupName="status"/>
<asp:RadioButton ID="rdoDateRange" runat="server" class="bodycontent"
GroupName="status" oncheckedchanged="rdoDateRange_CheckedChanged" AutoPostBack="true"
/>
<asp:UpdatePanel ID="Update" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtDays" runat="server" CssClass="bodycontent" MaxLength="6" ReadOnly="true"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdoDateRange" />
</Triggers>
</asp:UpdatePanel>
and
protected void rdoDateRange_CheckedChanged(object sender, EventArgs e)
{
DateTime startdate=Convert.ToDateTime(txtOStartDate.Text);
DateTime enddate=Convert.ToDateTime(txtOEndDate.Text);
var result = (enddate - startdate).TotalDays;
txtDays.Text =Convert.ToString( result);
}
Any suggestion?
its happening because you are forcing only post back on rdoDateRange...and when the other rdoSpecifiedDates is clicked no postback occur so that's why you rdoDateRange dose not reflect any change..
So make the rdoSpecifiedDates AutoPostBack = true.
hmm...either you have to put both rdobuttons in your trigger.. like this
<asp:RadioButton ID="rdoSpecifiedDates" runat="server" AutoPostBack="true" class="bodycontent" GroupName="status" />
<asp:RadioButton ID="rdoDateRange" runat="server" class="bodycontent" GroupName="status"
OnCheckedChanged="rdoDateRange_CheckedChanged" AutoPostBack="true" />
<asp:UpdatePanel ID="Update" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtDays" runat="server" CssClass="bodycontent" MaxLength="6" ReadOnly="true"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdoDateRange" />
<asp:AsyncPostBackTrigger ControlID="rdoSpecifiedDates" />
</Triggers>
</asp:UpdatePanel>
OR
Put both the radio buttons in update pannel like this..
<asp:UpdatePanel ID="Update" runat="server">
<ContentTemplate>
<asp:RadioButton ID="rdoSpecifiedDates" runat="server" AutoPostBack="true" class="bodycontent"
GroupName="status" />
<asp:RadioButton ID="rdoDateRange" runat="server" class="bodycontent" GroupName="status"
OnCheckedChanged="rdoDateRange_CheckedChanged" AutoPostBack="true" />
<asp:TextBox ID="txtDays" runat="server" CssClass="bodycontent" MaxLength="6" ReadOnly="true"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdoDateRange" />
</Triggers>
</asp:UpdatePanel>
You Also can do..:
<div>
<asp:RadioButton ID="rdoSpecifiedDates" runat="server" class="bodycontent"
GroupName="status" oncheckedchanged="rdoSpecifiedDates_CheckedChanged" AutoPostBack="true" />
<asp:RadioButton ID="rdoDateRange" runat="server" class="bodycontent" GroupName="status"
OnCheckedChanged="rdoDateRange_CheckedChanged" AutoPostBack="true" />
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="Update1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:TextBox ID="txtDays" runat="server" CssClass="bodycontent" MaxLength="6" Enable="False"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</div>
And
protected void rdoDateRange_CheckedChanged(object sender, EventArgs e)
{
DateTime startdate = DateTime.Now.AddHours(2);
DateTime enddate = DateTime.Now.AddHours(5);
TimeSpan result = enddate - startdate;
txtDays.Text = result.ToString();
Update1.Update();
}
protected void rdoSpecifiedDates_CheckedChanged(object sender, EventArgs e)
{
}
If your radio buttons are outside of the update panel (and need to be so), the selected/checked item will never fire due to not having any JavaScript on its <input> tag, which is logical in the sense that the page thinks the element is already selected so why would it need to fire off back to the server when it is clicked?
But it obviously causes issues in this scenario because, as triggers for an update panel, it never "repaints" itself to reflect that the selected item has changed.
My workaround for this is to "repaint" the radio buttons as well by having them in their own <asp:UpdatePanel> control:
<asp:UpdatePanel ID="RadioButtonUpdate" runat="server">
<ContentTemplate>
<asp:RadioButton ID="rdoSpecifiedDates" runat="server" class="bodycontent"
GroupName="status" OnCheckedChanged="rdoSpecifiedDates_CheckedChanged" AutoPostBack="true" />
<asp:RadioButton ID="rdoDateRange" runat="server" class="bodycontent"
GroupName="status" OnCheckedChanged="rdoDateRange_CheckedChanged" AutoPostBack="true" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="Update" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtDays" runat="server" CssClass="bodycontent" MaxLength="6" ReadOnly="true"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdoDateRange" />
</Triggers>
</asp:UpdatePanel>
This feels to me like the cleanest solution outside of housing the radio buttons within the update panel you are wanting refreshed.

TextBoxes in UpdatePanel are causing PageRequestManagerServerErrorException

I'm trying to create a page that has some information in databound labels with and edit button. When the edit button is clicked, the information is replaced with TextBoxes bound to the same data. The data can then be modified, saved back to the DB and the TextBoxes replaced with updated Labels.
To start with, and to keep things simple, all I have is an UpdatePanel with a DataList and two buttons: EditButton and CancelButton (CancelButton is hidden by default). The DataList's ItemTemplate has two Panels: ViewPanel and EditPanel (EditPanel is hidden by default). When EditButton is clicked, I hide EditButton and the DataList's Items' ViewPanel, and show CancelButton and the DataList's Items' EditPanel.
Not a problem. Once this is done however, the CancelButton button will not work, throwing a PageRequestManagerServerErrorException.
Through some fiddling, I worked out this happens because there are databound text boxes on the EditPanel. If I don't bind data to the text boxes, everything works perfectly. Why doesn't this work?
Here's my code:
UpdatePanelTest.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UpdatePanelTest.aspx.cs" Inherits="WebLetterViewer.UpdatePanelTest" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
<asp:SqlDataSource ID="AllLettersDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ORMSTestConnectionString %>"
SelectCommand="SELECT * FROM [Letters] WHERE ([id] = #id)">
<SelectParameters>
<asp:ControlParameter ControlID="HiddenLetterID" DefaultValue="1" Name="id" PropertyName="Value" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID="HiddenLetterID" runat="server" Value="1" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:DataList ID="LettersDataList" runat="server" DataSourceID="AllLettersDataSource">
<ItemTemplate>
<asp:Panel ID="ViewPanel" runat="server">
<h2>Data1:</h2>
<asp:Label ID="data1Label" runat="server" BorderStyle="Solid" BorderWidth="1px" Height="100px" Text='<%# Eval("data1") %>' Width="500px" />
<h2>data2:</h2>
<asp:Label ID="data2Label" runat="server" BorderStyle="Solid" BorderWidth="1px" Height="100px" Text='<%# Eval("data2") %>' Width="500px" />
<h2>data3:</h2>
<asp:Label ID="data3Label" runat="server" BorderStyle="Solid" BorderWidth="1px" Height="100px" Text='<%# Eval("data3") %>' Width="500px" />
</asp:Panel>
<asp:Panel ID="EditPanel" runat="server" Visible="False">
<h2>data1:</h2>
<asp:TextBox ID="data1TextBox" runat="server" Height="100px" Text='<%# Eval("data1", "{0}") %>' TextMode="MultiLine" Width="500px"></asp:TextBox>
<h2>data2:</h2>
<asp:TextBox ID="data2TextBox" runat="server" Height="100px" Text='<%# Eval("data2", "{0}") %>' TextMode="MultiLine" Width="500px"></asp:TextBox>
<h2>data3:</h2>
<asp:TextBox ID="data3TextBox" runat="server" Height="100px" Text='<%# Eval("data3", "{0}") %>' TextMode="MultiLine" Width="500px"></asp:TextBox>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="EditButton" runat="server" onclick="EditButton_Click" Text="Edit" />
<asp:Button ID="CancelButton" runat="server" onclick="CancelButton_Click" Text="Cancel" Visible="False" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
UpdatePanelTest.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebLetterViewer{
public partial class UpdatePanelTest : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e){
}
protected void EditButton_Click(object sender, EventArgs e){
foreach (DataListItem item in LettersDataList.Items){
item.FindControl("ViewPanel").Visible = false;
item.FindControl("EditPanel").Visible = true;
}
EditButton.Visible = false;
CancelButton.Visible = true;
UpdatePanel1.Update();
}
protected void CancelButton_Click(object sender, EventArgs e){
foreach (DataListItem item in LettersDataList.Items){
item.FindControl("ViewPanel").Visible = true;
item.FindControl("EditPanel").Visible = false;
}
EditButton.Visible = true;
CancelButton.Visible = false;
UpdatePanel1.Update();
}
}
}
Put your EditPanel in a EditItemTemplate and use Commands , you are not using this control the way it was designed to be used:
How to: Allow Users to Edit Items in DataList Web Server Controls
Markup:
<asp:SqlDataSource ID="AllLettersDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ORMSTestConnectionString %>"
SelectCommand="SELECT * FROM [Letters] WHERE ([id] = #id)">
<SelectParameters>
<asp:ControlParameter ControlID="HiddenLetterID" DefaultValue="1" Name="id" PropertyName="Value"
Type="Int32" />
</SelectParameters>
<!--change this -->
UpdateCommand="UPDATE [Categories] SET [CategoryName] = #CategoryName, [Description]
= #Description WHERE [CategoryID] = #original_CategoryID">
<UpdateParameters>
<asp:Parameter Name="CategoryName" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="original_CategoryID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:DataList ID="LettersDataList" runat="server" DataSourceID="AllLettersDataSource"
OnEditCommand="LettersDataList_EditCommand" OnCancelCommand="LettersDataList_CancelCommand"
OnUpdateCommand="LettersDataList_UpdateCommand">
<ItemTemplate>
<asp:Panel ID="ViewPanel" runat="server">
<h2>
Data1:</h2>
<asp:Label ID="data1Label" runat="server" BorderStyle="Solid" BorderWidth="1px" Height="100px"
Text='<%# Eval("data1") %>' Width="500px" />
<h2>
data2:</h2>
<asp:Label ID="data2Label" runat="server" BorderStyle="Solid" BorderWidth="1px" Height="100px"
Text='<%# Eval("data2") %>' Width="500px" />
<h2>
data3:</h2>
<asp:Label ID="data3Label" runat="server" BorderStyle="Solid" BorderWidth="1px" Height="100px"
Text='<%# Eval("data3") %>' Width="500px" />
</asp:Panel>
<asp:Button ID="EditButton" runat="server" CommandName="edit" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Panel ID="EditPanel" runat="server">
<h2>
data1:</h2>
<asp:TextBox ID="data1TextBox" runat="server" Height="100px" Text='<%# Eval("data1", "{0}") %>'
TextMode="MultiLine" Width="500px"></asp:TextBox>
<h2>
data2:</h2>
<asp:TextBox ID="data2TextBox" runat="server" Height="100px" Text='<%# Eval("data2", "{0}") %>'
TextMode="MultiLine" Width="500px"></asp:TextBox>
<h2>
data3:</h2>
<asp:TextBox ID="data3TextBox" runat="server" Height="100px" Text='<%# Eval("data3", "{0}") %>'
TextMode="MultiLine" Width="500px"></asp:TextBox>
</asp:Panel>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="update">
Save
</asp:LinkButton>
<asp:Button ID="CancelButton" runat="server" CommandName="cancel" Text="Cancel" Visible="False" />
</EditItemTemplate>
</asp:DataList>
Code-behind:
protected void LettersDataList_EditCommand(object source, DataListCommandEventArgs e)
{
LettersDataList.EditItemIndex = e.Item.ItemIndex;
LettersDataList.DataBind();
}
protected void LettersDataList_CancelCommand(object source,
DataListCommandEventArgs e)
{
LettersDataList.EditItemIndex = -1;
LettersDataList.DataBind();
}
protected void LettersDataList_UpdateCommand(object source,
DataListCommandEventArgs e)
{
//change this to your database needs
//String categoryID =
// LettersDataList.DataKeys[e.Item.ItemIndex].ToString();
//String categoryName =
// ((TextBox)e.Item.FindControl("textCategoryName")).Text;
//String description =
// ((TextBox)e.Item.FindControl("textDescription")).Text;
//SqlDataSource1.UpdateParameters["original_CategoryID"].DefaultValue
// = categoryID;
//SqlDataSource1.UpdateParameters["categoryName"].DefaultValue
// = categoryName;
//SqlDataSource1.UpdateParameters["Description"].DefaultValue
// = description;
//SqlDataSource1.Update();
LettersDataList.EditItemIndex = -1;
LettersDataList.DataBind();
}

Categories