ASP.NET C# WebForms ListView Highlight Item When Clicking - c#

I am trying to have the clicked on(selected) ListView item be highlighted. However what is currently happening is the last selected item is being highlighted instead.
Here is my asp.net code:
<asp:ListView ID="UsersListView" AutoPostBack="true" runat="server" OnSelectedIndexChanging="UsersListView_SelectedIndexChanging" OnSelectedIndexChanged="UsersListView_SelectedIndexChanged" >
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr>
<td id="itemPlaceholder" runat="server">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" runat="server" Text='<%# Container.DataItem %>'/>
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr runat="server" style="background-color: #336699;">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" runat="server" Text='<%# Container.DataItem %>' BackgroundColor="#336699" ForeColor="White" />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
Here is my C# code beside:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<string> users = new List<string>()
{
"Gary",
"Joe",
"Brian"
};
UsersListView.DataSource = users;
UsersListView.DataBind();
}
}
protected void UsersListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
UsersListView.SelectedIndex = e.NewSelectedIndex;
}
protected void UsersListView_SelectedIndexChanged(object sender, EventArgs e)
{
}
Thank you for your help.

You have to use OnCommand for link button or use ListViewItemCommand and pass Item.DisplayIndex as argument to linkButton attribute CommandArgument while you are selecting item and in your case when link button is not to highlight because you are focusing on selecting not over LinkButton.So do your code on Server Side for HighLight Item Button.
Aspx
<asp:ListView ID="UsersListView" AutoPostBack="true" runat="server" OnSelectedIndexChanged="UsersListView_SelectedIndexChanged" OnItemCommand="UsersListView_ItemCommand" OnSelectedIndexChanging="UsersListView_SelectedIndexChanging">
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr>
<td id="itemPlaceholder" runat="server">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" OnCommand="UserNameLinkButton_Command" CommandArgument="<%# Container.DisplayIndex %>" runat="server" Text='<%# Container.DataItem %>'/>
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr runat="server">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" CommandArgument="<%# Container.DisplayIndex %>" runat="server" Text='<%# Container.DataItem %>' ForeColor="White" />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
cs(Code)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> users = new List<string>()
{
"Gary",
"Joe",
"Brian"
};
UsersListView.DataSource = users;
UsersListView.DataBind();
}
}
int selectedIndex=0;
protected void UsersListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
foreach(var item in UsersListView.Items)
{
LinkButton reset=item.FindControl("UserNameLinkButton") as LinkButton;
reset.BackColor = System.Drawing.Color.White;
reset.ForeColor = System.Drawing.Color.Blue;
}
LinkButton linkButton = (e.Item.FindControl("UserNameLinkButton")) as LinkButton;
linkButton.BackColor = System.Drawing.ColorTranslator.FromHtml("#336699");
linkButton.ForeColor = System.Drawing.Color.White;
}
protected void UsersListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
}
protected void UsersListView_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void UserNameLinkButton_Command(object sender, CommandEventArgs e)
{
//you can also do work here for when one of link button give command.(clicked)
}
Tested

Related

hide column in an asp.net listview?

I have below list view , how can i hide column by code behind ?
<asp:ListView ID="AuditLogListView" runat="server" OnItemCreated="AuditLogListView_ItemCreated">
<LayoutTemplate>
<table class="table table-striped table-bordered small">
<tr class="table-secondary">
<th id="BlockHeader" runat="server" style="white-space: normal;">
<asp:Literal ID="BlockHeaderLiteral" runat="server" Text="<%$ Resources:AppResources, AuditInformationBlockHeader %>" />
</th>
</tr>
<asp:PlaceHolder runat="server" ID="ItemPlaceholder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td id="BlockStatus" runat="server">
<%# Eval("BlockStatus")%>
</td>
</tr>
</ItemTemplate>
After binding data with list view i tried below code behind but with this header text only hide but column still can still visible
if (groupOrBlockValue == 'W')
{
AuditLogListView.FindControl("BlockHeader").Visible = false;
AuditLogListView.FindControl("BlockHeaderLiteral").Visible = false;
//AuditLogListView.FindControl("BlockStatus").Visible = false;
}
Missing part of the list view?
With this:
<asp:ListView ID="LstMarks" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr style="">
<td><asp:Textbox ID="Course" runat="server" Text='<%# Eval("Course") %>' /></td>
<td><asp:Textbox ID="Mark" runat="server" Text='<%# Eval("Mark") %>' Width="30px"/></td>
<td>
<asp:CheckBox ID="DoneLabs" runat="server" Checked = '<%# Eval("DoneLabs") %>' Width="30px"/>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" class="table">
<tr runat="server" style="">
<th runat="server" >Course</th>
<th runat="server">Mark</th>
<th id= "LabW" runat="server" >Completed Lab Work</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
<br />
<br />
<asp:Button ID="cmdHide" runat="server" Text="Hide Lab check box" OnClick="cmdHide_Click" />
So note in the layout, we added a "id" = LabW - that lets you hide the header.
so, a simple button that would toggle (hide/show) the lvColum, then this works:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from StudentCourses",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
LstMarks.DataSource = cmdSQL.ExecuteReader();
LstMarks.DataBind();
}
}
}
protected void cmdHide_Click(object sender, EventArgs e)
{
Control ctrHeader = LstMarks.FindControl("LabW");
ctrHeader.Visible = !ctrHeader.Visible;
foreach (ListViewItem lvRow in LstMarks.Items)
{
CheckBox ckBox = (CheckBox)lvRow.FindControl("DoneLabs");
ckBox.Visible = !ckBox.Visible;
}
}
So, we get this:
And clicking on the button, we get this:
And both the values changed - they persist - even when you click again (to toggle and show the hidden columns).
Edit: =====================================================
So, say this markup:
<asp:ListView ID="AuditLogListView" runat="server"
OnItemCreated="AuditLogListView_ItemCreated">
<LayoutTemplate>
<table class="table table-striped table-bordered small">
<tr class="table-secondary">
<th id="BlockHeader" runat="server" style="white-space: normal;">
<asp:Literal ID="BlockHeaderLiteral" runat="server" Text="Hotel Name" />
</th>
</tr>
<asp:PlaceHolder runat="server" ID="ItemPlaceholder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td id="BlockStatus" runat="server">
<%# Eval("BlockStatus")%>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
And code behind button to hide is this:
protected void Button1_Click(object sender, EventArgs e)
{
Control ctrHeader = AuditLogListView.FindControl("BlockHeaderLiteral");
ctrHeader.Visible = !ctrHeader.Visible;
foreach (ListViewItem lvRow in AuditLogListView.Items)
{
Control BlockStat = (Control)lvRow.FindControl("BlockStatus");
BlockStat.Visible = !BlockStat.Visible;
}
}
At which event have you written this code?
Required this code in the OnDataBound event. And in your code this event missing.
<asp:ListView ID="AuditLogListView" runat="server" OnItemCreated="AuditLogListView_ItemCreated" OnDataBound="AuditLogListView_DataBound">
<asp:Literal ID="BlockHeaderLiteral" runat="server" Text="<%$ Resources:AppResources, AuditInformationBlockHeader %>" /><asp:PlaceHolder runat="server" ID="ItemPlaceholder"></asp:PlaceHolder>
C# Code:
protected void AuditLogListView_DataBound(object sender, EventArgs e)
{AuditLogListView.FindControl("BlockHeaderLiteral").Visible = false;}

using click event of dynamically created button inside dynamically created accordionpane

I have a method that generates accordionpanes and panels and inside each accordionpane I create a button. This methode I use it in the listviewselectedindexchanged method to create the order object and fillup the body panel
protected void PanelCreator(Order order, List<Panel> pnllist)
{
Panel panelHead = new Panel();
panelHead.ID = "pH" + order.product;
panelHead.CssClass = "cpHeader";
//Add Label inside header panel to display text
Label lblHead = new Label();
lblHead.ID = order.product;
lblHead.Text = order.productName + " €" + order.priceValue;
panelHead.Controls.Add(lblHead);
//Create Body Panel
Panel panelBody = new Panel();
panelBody.ID = "pB" + order.product;
panelBody.CssClass = "cpBody";
AccordionPane ap = new AccordionPane();
foreach (Panel p in pnllist)
{
panelBody.Controls.Add(p);
}
Button btn = new Button();
btn.ID = "btn" + order.product;
btn.Text = "Toevoegen";
btn.Click += new EventHandler(btn_Click);
panelHead.Controls.Add(btn);
ap.ID = "ap" + order.product;
ap.HeaderContainer.Controls.Add(panelHead);
ap.ContentContainer.Controls.Add(panelBody);
accMenu.Panes.Add(ap);
}
I am trying to reach each buttons click event but don't know how to do it.
I have this method as for the click event to test a label inside the updatepanel but not working
protected void btn_Click(object sender, EventArgs e)
{
nameLabel.Text = "testinf";
}
this is my aspx page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Label ID="nameLabel" runat="server" Text="aa" />
<div style="overflow-x: auto;">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="main_product_id" DataSourceID="odsMainProduct" OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
<stackpanel orientation="Horizontal" />
<td>
<asp:LinkButton ID="lnkSelect" runat="server" CommandName="Select" Font-Overline="false" Font-Bold="true" Font-Size="15px" Height="30px" Text='<%# Eval("name") %>' />
<%--<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />--%></td>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="color: white; text-align: left; width: auto">
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style=""></td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<td>
<asp:LinkButton ID="lnkSelect0" runat="server" CommandName="Select" Font-Overline="false" Font-Size="20px" ForeColor="red" Height="30px" Text='<%# Eval("name") %>' />
<%--<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />--%></td>
</SelectedItemTemplate>
</asp:ListView>
</div>
<asp:ObjectDataSource ID="odsMainProduct" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetMainProducts" TypeName="MainProductBLL"></asp:ObjectDataSource>
<asp:Accordion ID="accMenu" runat="server"></asp:Accordion>
</ContentTemplate>
</asp:UpdatePanel>
You need to store your button creation data in ViewState for creating these controls in page-load event, after that button click will be processed correct.
Order class should be marked as Serializable
public Order SelectedOrder
{
get
{
return ViewState["StoredOrder"] == null ? (Order)ViewState["StoredOrder"] : null;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (SelectedOrder != null)
{
PanelCreator(SelectedOrder);
}
}
protected void listviewselectedindexchanged(object sender, System.EventArgs e)
{
// I am not sure how you got order in this event, you should use your version of code, but idea is the same
ViewState["StoredOrder"] = sender as Order;
PanelCreator(SelectedOrder);
}

How to change image source inside LinkButton in Repeater Asp.Net C#

I am trying to get image inside LinkButton in Repeater and wanted to change image Src but it does not changing image UI side.
HTMl Code:
<asp:Repeater ID="Repeater" runat="server" OnItemCommand="Repeater_ItemCommand" >
<HeaderTemplate>
<table c>
<tr>
<th>
<asp:LinkButton ID="lbtnC1" CommandName="Col1" runat="server">Column1 <asp:Image id="imgStamp" ClientIDMode="AutoID" runat="server" style="vertical-align:middle;padding-left:3px" /></asp:LinkButton>
</thalign>
<th>
<asp:LinkButton ID="lbtnC2" runat="server"
CommandName="Col2">Column2 <asp:Image id="imgStamp" ClientIDMode="AutoID" runat="server" style="vertical-align:middle;padding-left:3px" /></asp:LinkButton></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Literal ID="C1Value" runat="server" />
</td>
<td>
<asp:Literal ID="C2Value" runat="server" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
C# Event
protected void Repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
LinkButton linkButton = e.CommandSource as LinkButton;
HtmlImage image = linkButton.Controls[0] as HtmlImage;
if (e.CommandName == "Col1")
{
image.Src = Page.ResolveUrl("~/arrow-down-white.gif");
}
}
Change it to HtmlImage image = linkButton.Controls[1] as HtmlImage;
I believe (but not 100% sure) that the first control is a Literal.
By doing this i'm able to solve my issue.
protected void Repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
Image imgStamp = Repeater.Controls[0].Controls[0].FindControl("imgStamp") as Image;
imgStamp.ImageUrl = Page.ResolveUrl("URL");
}

Compilation Error CS0120 in a temporary file (C#)

I've just taken over a C#/.NET project last touched a few years ago with with the task of updating it and including more functionality. I have no experience with the platform and so am struggling to fix this error.
The system is currently live (and works), but I've gotten a copy running on my machine and I get the following error which I cannot seem to figure out to get it up and running:
Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property '<ProjectName>.<PageName>.System'
Source Error:
Line 195:
Line 196: private static System.Reflection.MethodInfo #__PageInspector_LoadHelper(string helperName) {
Line 197: System.Type helperClass = System.Type.GetType("Microsoft.VisualStudio.Web.PageInspector.Runtime.WebForms.TraceHelpers, Microsoft" +
Line 198: ".VisualStudio.Web.PageInspector.Tracing, Version=2.0.0.0, Culture=neutral, Publi" +
Line 199: "cKeyToken=b03f5f7f11d50a3a", false, false);
I've established from other questions that this error is normally caused when using non-static fields and methods incorrectly like this or this, but in my case it seems to be coming from a temporary file, which I have no control over?
UPDATE: The Admin.aspx file is below:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/Admin.Master" AutoEventWireup="false"
EnableEventValidation="false" CodeBehind="Admin.aspx.cs" Inherits="CallLog.Admin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="AdminContent1" runat="server">
<div id="System" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>SYSTEM</i>
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddAppSystem" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddAppSystem" CssClass="Save" runat="server" Text="Add New System"
OnClick="btnAddAppSystem_Click" ValidationGroup="appsystem" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ValidationGroup="appsystem" ControlToValidate="txtAddAppSystem" ErrorMessage="Please Add System" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvAppSystem" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="AppSystemId" OnRowCancelingEdit="gvAppSystem_RowCancelingEdit"
OnRowEditing="gvAppSystem_RowEditing" OnRowUpdating="gvAppSystem_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="appSystemId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="System" ItemStyle-Width="150px">
<ItemTemplate>
&nbsp &nbsp
<%# Eval("appSystemDesc")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtAppSystem" Text='' value='<%# Eval ("appSystemDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminContent2" runat="server">
<div id="Div1" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>STATUS</i>
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddStatus" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="status" runat="server" ControlToValidate="txtAddStatus" ErrorMessage="Please Add Status" CssClass="Warning"></asp:RequiredFieldValidator>
<asp:Button ID="btnAddStatus" CssClass="Save" runat="server" ValidationGroup="status" Text="Add New Status"
OnClick="btnAddStatus_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvStatus" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="statusId" OnRowCancelingEdit="gvStatus_RowCancelingEdit"
OnRowEditing="gvStatus_RowEditing" OnRowUpdating="gvStatus_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="statusId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Status" ItemStyle-Width="150px">
<ItemTemplate>
&nbsp &nbsp
<%# Eval("statusDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtStatus" Text='' value='<%# Eval ("statusDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="AdminContent3" runat="server">
<div id="Jurisdiction" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>JURISDICTION</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddJurisdiction" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddJurisdiction" CssClass="Save" runat="server" ValidationGroup="juridiction" Text="Add New Jurisdiction"
OnClick="btnAddJurisdiction_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ValidationGroup="juridiction" ControlToValidate="txtAddJurisdiction" ErrorMessage="Please Add Juridiction" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvJurisdiction" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="jurisdictionId" OnRowCancelingEdit="gvJurisdiction_RowCancelingEdit"
OnRowEditing="gvJurisdiction_RowEditing" OnRowUpdating="gvJurisdiction_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="jurisdictionId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Jurisdiction" ItemStyle-Width="150px">
<ItemTemplate>
&nbsp &nbsp
<%# Eval("jurisdictionDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtJurisdiction" Text='' value='<%# Eval ("jurisdictionDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="AdminContent4" runat="server">
<div id="Impact" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>IMPACT</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtImpact" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnImpact" CssClass="Save" runat="server" Text="Add New Impact" ValidationGroup="impact" OnClick="btnAddImpact_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtImpact" ValidationGroup="impact" ErrorMessage="Please Add Impact" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvImpact" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="impactId" OnRowCancelingEdit="gvImpact_RowCancelingEdit"
OnRowEditing="gvImpact_RowEditing" OnRowUpdating="gvImpact_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="impactId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Impact" ItemStyle-Width="150px">
<ItemTemplate>
&nbsp &nbsp
<%# Eval("impactDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtImpact" Text='' value='<%# Eval ("impactDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="AdminContent5" runat="server">
<div id="Period" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>PERIOD</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddPeriod" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddPeriod" CssClass="Save" runat="server" ValidationGroup="period" Text="Add New Period"
OnClick="btnAddPeriod_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ValidationGroup="period" ControlToValidate="txtAddPeriod" ErrorMessage="Please Add Period" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvPeriod" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="periodId" OnRowCancelingEdit="gvPeriod_RowCancelingEdit"
OnRowEditing="gvPeriod_RowEditing" OnRowUpdating="gvPeriod_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="periodId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Period" ItemStyle-Width="150px">
<ItemTemplate>
&nbsp &nbsp
<%# Eval("periodDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPeriod" Text='' value='<%# Eval ("periodDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="AdminContent6" runat="server">
<div id="Issue" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>ISSUE</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddIssue" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddIssue" CssClass="Save" runat="server" ValidationGroup="issue" Text="Add New Issue"
OnClick="btnAddIssue_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ValidationGroup="issue" ControlToValidate="txtAddIssue" ErrorMessage="Please Add Issue" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvIssue" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="issueId" OnRowCancelingEdit="gvIssue_RowCancelingEdit"
OnRowEditing="gvIssue_RowEditing" OnRowUpdating="gvIssue_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="issueId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Issue" ItemStyle-Width="150px">
<ItemTemplate>
&nbsp &nbsp
<%# Eval("issueDesc")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtIssue" Text='' value='<%# Eval ("issueDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
UPDATE 2: The Admin.aspx.cs file below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Midtier.DAL;
namespace CallLog
{
public partial class Admin : System.Web.UI.Page
{
AdminDisplay ad = new AdminDisplay();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
listJurisdictions();
listImpact();
listStatus();
listPeriod();
listAppSystem();
listIssue();
}
}
#region AppSystem
public void listAppSystem()
{
gvAppSystem.DataSource = ad.getAppSystem();
gvAppSystem.DataBind();
}
protected void gvAppSystem_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddAppSystem.Enabled = false;
gvAppSystem.EditIndex = e.NewEditIndex;
listAppSystem();
}
protected void gvAppSystem_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvAppSystem.EditIndex = -1;
listAppSystem();
}
protected void gvAppSystem_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvAppSystem.Rows[e.RowIndex];
TextBox txtAppSystemDesc = (TextBox)row.FindControl("txtAppSystem");
int appSystemID = Int32.Parse(gvAppSystem.DataKeys[e.RowIndex].Value.ToString());
string appSystemDesc = txtAppSystemDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditAppSystem(appSystemID, appSystemDesc);
gvAppSystem.EditIndex = -1;
listAppSystem();
btnAddAppSystem.Enabled = true;
}
protected void btnAddAppSystem_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditAppSystem(-1, txtAddAppSystem.Text);
listAppSystem();
txtAddStatus.Text = "";
}
#endregion
#region Status
public void listStatus()
{
gvStatus.DataSource = ad.getStatus();
gvStatus.DataBind();
}
protected void gvStatus_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddStatus.Enabled = false;
gvStatus.EditIndex = e.NewEditIndex;
listStatus();
}
protected void gvStatus_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvStatus.EditIndex = -1;
listStatus();
}
protected void gvStatus_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvStatus.Rows[e.RowIndex];
TextBox txtStatusDesc = (TextBox)row.FindControl("txtStatus");
int statusID = Int32.Parse(gvStatus.DataKeys[e.RowIndex].Value.ToString());
string statusDesc = txtStatusDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditStatus(statusID, statusDesc);
gvStatus.EditIndex = -1;
listStatus();
btnAddStatus.Enabled = true;
}
protected void btnAddStatus_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditStatus(-1, txtAddStatus.Text);
listStatus();
txtAddStatus.Text = "";
}
#endregion
#region Jurisdiction
private void listJurisdictions()
{
gvJurisdiction.DataSource = ad.getJurisdiction();
gvJurisdiction.DataBind();
}
protected void gvJurisdiction_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddJurisdiction.Enabled = false;
gvJurisdiction.EditIndex = e.NewEditIndex;
listJurisdictions();
}
protected void gvJurisdiction_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvJurisdiction.EditIndex = -1;
listJurisdictions();
}
protected void gvJurisdiction_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvJurisdiction.Rows[e.RowIndex];
TextBox txtJurisdictionDesc = (TextBox)row.FindControl("txtJurisdiction");
int jurisdictionID = Int32.Parse(gvJurisdiction.DataKeys[e.RowIndex].Value.ToString());
string jurisdictionDesc = txtJurisdictionDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditJurisdiction(jurisdictionID, jurisdictionDesc);
gvJurisdiction.EditIndex = -1;
listJurisdictions();
btnAddJurisdiction.Enabled = true;
}
protected void btnAddJurisdiction_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditJurisdiction(-1, txtAddJurisdiction.Text);
listJurisdictions();
txtAddJurisdiction.Text = "";
}
#endregion
#region Impact
private void listImpact()
{
gvImpact.DataSource = ad.getImpact();
gvImpact.DataBind();
}
protected void gvImpact_RowEditing(object sender, GridViewEditEventArgs e)
{
btnImpact.Enabled = false;
gvImpact.EditIndex = e.NewEditIndex;
listImpact();
}
protected void gvImpact_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvImpact.EditIndex = -1;
listImpact();
}
protected void gvImpact_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvImpact.Rows[e.RowIndex];
TextBox txtImpactDesc = (TextBox)row.FindControl("txtImpact");
int impactID = Int32.Parse(gvImpact.DataKeys[e.RowIndex].Value.ToString());
string impactDesc = txtImpactDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditImpact(impactID, impactDesc);
gvImpact.EditIndex = -1;
listImpact();
btnImpact.Enabled = true;
}
protected void btnAddImpact_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditImpact(-1, txtImpact.Text);
listImpact();
txtImpact.Text = "";
}
#endregion
#region Period
private void listPeriod()
{
gvPeriod.DataSource = ad.getPeriod();
gvPeriod.DataBind();
}
protected void gvPeriod_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddPeriod.Enabled = false;
gvPeriod.EditIndex = e.NewEditIndex;
listPeriod();
}
protected void gvPeriod_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvPeriod.EditIndex = -1;
listPeriod();
}
protected void gvPeriod_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvPeriod.Rows[e.RowIndex];
TextBox txtPeriodDesc = (TextBox)row.FindControl("txtPeriod");
int periodID = Int32.Parse(gvPeriod.DataKeys[e.RowIndex].Value.ToString());
string periodDesc = txtPeriodDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditPeriod(periodID, periodDesc);
gvPeriod.EditIndex = -1;
listPeriod();
btnAddPeriod.Enabled = true;
}
protected void btnAddPeriod_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditPeriod(-1, txtAddPeriod.Text);
listPeriod();
txtAddPeriod.Text = "";
}
#endregion
#region Issue
private void listIssue()
{
gvIssue.DataSource = ad.getIssue();
gvIssue.DataBind();
}
protected void gvIssue_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddIssue.Enabled = false;
gvIssue.EditIndex = e.NewEditIndex;
listIssue();
}
protected void gvIssue_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvIssue.EditIndex = -1;
listIssue();
}
protected void gvIssue_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvIssue.Rows[e.RowIndex];
TextBox txtIssueDesc = (TextBox)row.FindControl("txtIssue");
int issueID = Int32.Parse(gvIssue.DataKeys[e.RowIndex].Value.ToString());
string issueDesc = txtIssueDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditIssue(issueID, issueDesc);
gvIssue.EditIndex = -1;
listIssue();
btnAddIssue.Enabled = true;
}
protected void btnAddIssue_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditIssue(-1, txtAddIssue.Text);
listIssue();
txtAddIssue.Text = "";
}
#endregion
}
}
I think, you are having same name for both class and namespace, could you please check, it might be the cause of this issue.
As, usual, I found the solution to my own problem (two cups of coffee and eight full hours of sleep later - not in that order).
The problem was that in Admin.aspx, the first div with id=System forced the Admin.aspx.designer.cs file to generate a System.Web.UI.HtmlControls.HtmlGenericControl variable called System.
This caused some sort of confusion for the compiler (is that even an actual thing?) because of the System namespace.
This was a good lesson in what not to do.

ASP.NET loses data from form after postback - repeater inside updatepanel inside repeater

I have a ASP.NET web form where I have few checkboxes etc to make SearchCriteria object. When I click submit button I ask repeater1 to shew some records according to SearchCriteria. Inside repeater1 I have user control with updatepanel and another one repeater (ChildRepeater).
My problem: when I click send on the button after postback I lose all the data from form (eg that checkboxes was checked). Page is loading default values, but in my code I load default (all checkboxes checked) only if(!IsPostBack).
Of course I have "EnableViewState=true" in .aspx, I also tried to save data from form in session, but it also does not work (default values rewrite this settings).
When I have only one repeater (repeater1) my form after postback had all the data I put on it, so I think that there is some problem in updatepanel, but I don't know where exactly.
Could you explain me why my form loses data after page reload? I can't see any mistake..
At the bottom are my files but I have n-tier architecture so... i put only necessary files from View/BLL (DAL and sql connection works fine)
Here you have a screen how it looks: screen
ShowAgreements.aspx (it contains controls and parent repeater):
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table style="border: 1px solid #0000FF; width: 1250px">
<tr style="background-color: #3d6db0; color: #000000; font-weight: bold;">
<td style="width: 150px;">Numer</td>
<td style="width: 150px;">Przedmiot umowy</td>
<td style="width: 150px;">Odbiorca</td>
<td style="width: 150px;">Dostawca</td>
<td style="width: 150px;">Rodzaj umowy</td>
<td style="width: 150px;">Charakter umowy</td>
<td style="width: 150px;">Status wypożyczenia</td>
<td style="width: 150px;">Data podpisania</td>
<td style="width: 150px;">Status</td>
</tr>
</HeaderTemplate>
<itemtemplate>
<uc1:FilesRepeaterControl runat="server" id="FilesRepeaterControl" />
</itemtemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
ShowAgreements.aspx.cs:
AgreementsSearchCriteria AgreementSearchCriteriaObj = new AgreementsSearchCriteria();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Controller.ReadDostawcy();
Controller.ReadOdbiorcy();
Controller.ReadPracownikOdp();
}
Controller.ReadAllAgreements();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Agreement umowa = e.Item.DataItem as Agreement;
BazaUmow.Controls.FilesRepeaterControl test = e.Item.FindControl("FilesRepeaterControl") as FilesRepeaterControl;
test.umowa = umowa;
}
}
protected void szukaj_Click(object sender, EventArgs e)
{
if (IsValid == true)
{
AddNaviPoint();
Controller.ReadAllAgreements();
}
}
public AgreementSearchCollection BindUmowyResults
{
set
{
Repeater1.DataSource = value;
Repeater1.DataBind();
}
}
FilesRepeaterControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="FilesRepeaterControl.ascx.cs" Inherits="BazaUmow.Controls.FilesRepeaterControl" %>
<tr>
<td style="width: 150px">
<asp:Button ID="btnRozwin" runat="server" Text="+" OnClick="btnRozwin_Click" />
<asp:LinkButton ID="lbl_numerUmowy" runat="server" OnClick="lbl_numerUmowy_Click"></asp:LinkButton>
</td>
<td style="width: 150px">
<asp:Label ID="lbl_przedmiotUmowy" runat="server" /></td>
<td style="width: 150px">
<asp:Label ID="lbl_odbiorca" runat="server" /></td>
<td style="width: 150px">
<asp:Label ID="lbl_dostawca" runat="server" /></td>
<td style="width: 150px">
<asp:Label ID="lbl_rodzajUmowy" runat="server" /></td>
<td style="width: 150px">
<asp:Label ID="lbl_charakterUmowy" runat="server" /></td>
<td style="width: 150px">
<asp:Label ID="lbl_statusWypozyczenia" runat="server" /></td>
<td style="width: 150px">
<asp:Label ID="lbl_dataPodpisania" runat="server" /></td>
<td style="width: 150px">
<asp:Label ID="lbl_statusUmowy" runat="server" /></td>
</tr>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanelFilesInfo" runat="server">
<ContentTemplate>
<asp:Repeater ID="filesRptr" runat="server" OnItemDataBound="filesRptr_ItemDataBound">
<HeaderTemplate>
<table style=" width:170px">
<tr style="font-weight: bold;">
<td style="width:170px;">Pliki umowy</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="lblPlikUmowy" runat="server" OnCommand="lblPlikUmowy_Command"></asp:LinkButton></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:Repeater ID="aneksyRptr" runat="server" OnItemDataBound="aneksyRptr_ItemDataBound">
<HeaderTemplate>
<table style=" width:170px">
<tr style="font-weight: bold;">
<td style="width:170px;">Aneksy do umowy</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="lblAneksUmowy" runat="server" OnCommand="lblAneksUmowy_Command"></asp:LinkButton></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
FilesRepeaterControl.ascx.cs (here we add data to parent repeater and fill two child repeaters when we click button btnRozwin)
public Agreement umowa { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
lbl_numerUmowy.Text = umowa.numer_umowy.ToString();
lbl_przedmiotUmowy.Text = umowa.przedmiot_umowy.ToString();
lbl_odbiorca.Text = umowa.odbiorca_tekst.ToString();
lbl_dostawca.Text = umowa.dostawca_tekst.ToString();
lbl_rodzajUmowy.Text = umowa.rodzaj_umowy_tekst.ToString();
lbl_charakterUmowy.Text = umowa.charakter_umowy_tekst.ToString();
lbl_statusWypozyczenia.Text = umowa.status_wypozyczenia_tekst.ToString();
lbl_dataPodpisania.Text = umowa.data_podpisania.ToString("yyyy-MM-dd");
lbl_statusUmowy.Text = umowa.status_umowy.ToString();
}
protected void filesRptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Plik plik = e.Item.DataItem as Plik;
LinkButton lblPlikUmowy = e.Item.FindControl("lblPlikUmowy") as LinkButton;
lblPlikUmowy.Text = plik.nazwa_pliku.ToString();
lblPlikUmowy.CommandArgument = plik.guid + plik.rozszerzenie;
}
}
protected void aneksyRptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Plik plik = e.Item.DataItem as Plik;
LinkButton lblAneksUmowy = e.Item.FindControl("lblAneksUmowy") as LinkButton;
lblAneksUmowy.Text = plik.nazwa_pliku.ToString();
lblAneksUmowy.CommandArgument = plik.guid + plik.rozszerzenie;
}
}
protected void btnRozwin_Click(object sender, EventArgs e)
{
if (btnRozwin.Text == "+")
{
filesRptr.Visible = true;
aneksyRptr.Visible = true;
filesRptr.DataSource = Controller.ReadFilesByAgreement(Convert.ToInt32(lbl_numerUmowy.Text), 1);
filesRptr.DataBind();
aneksyRptr.DataSource = Controller.ReadFilesByAgreement(Convert.ToInt32(lbl_numerUmowy.Text), 2);
aneksyRptr.DataBind();
btnRozwin.Text = "-";
}
else
{
filesRptr.Visible = false;
aneksyRptr.Visible = false;
btnRozwin.Text = "+";
}
}
protected void lbl_numerUmowy_Click(object sender, EventArgs e)
{
string numer_umowy = ((LinkButton)sender).Text;
Page.Response.Redirect("~/SeeAgreementData.aspx?numer=" + numer_umowy + "&email=" + Request.QueryString["email"]);
}
}
It is because when you post back your update panel it refreshes a part(which is surrounded with update panel) of the page, so all data that was on that pannel is lost you can save all data that you need in ViewState
protected void UpdatePanelClick_OnClick(object sender, EventArgs e)
{
List<int> checkedIds = new List<int>();
//working with grid saving ids on list
ViewState["saveUpdatePanelData"] = checkedIds;
}
than on pageload after postback you can get this data and initialize
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["saveUpdatePanelData"]!= null)
{
checkedIds = ViewState["saveUpdatePanelData"] as List<int>;
}
}
it is how ViewState works.

Categories