How to delete specific listview items in ASP.NET C#? - c#

Here is my messageview.aspx, which has list view to show user messages.
On delete button click, I want to capture the current table row value, and call the sql stored procedure accordingly. However, I am unable to access the fields like Sender Email-ID, Sender Role, and Message inside delete button click function. how can I do so?
<%# Page Title="" Language="C#" MasterPageFile="~/DefaultLayout.Master" AutoEventWireup="true" CodeBehind="MessageView.aspx.cs" Inherits="SchoolMgmtSystem.MessageView" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="jumbotron">
<h1>Inbox</h1>
</div>
<asp:ListView ID="lvgetMessages" runat="server" OnSelectedIndexChanged="lvgetMessages_SelectedIndexChanged">
<EmptyDataTemplate>
<table runat="server" style="background-color: #FFFFFF; border-collapse: collapse; border-color: #999999; border-style: none; border-width: 1px;">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<LayoutTemplate>
<table class="table table-border">
<tr>
<th> Sender Email ID</th>
<th> Sender Role </th>
<th> Message</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #DCDCDC; color: #000000;">
<td>
<asp:Label ID="emailIDLabel" runat="server" Text='<%# Eval("[SenderEmailID]") %>' />
</td>
<td>
<asp:Label ID="SenderRoleLabel" runat="server" Text='<%# Eval("RoleName") %>' />
</td>
<td>
<asp:Label ID="MessageLabel" runat="server" Text='<%# Eval("[Message]") %>' />
</td>
<td>
<asp:Button ID="ButtonDelete" runat="server" Text="Delete" onclick="ButtonDelete_Click" UseSubmitBehavior="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<div class="form-group" runat="server" style="display:block">
<asp:Button ID="ButtonBack" runat="server" Text="Back" CssClass="btn-primary center-block" OnClick="ButtonBack_Click" />
</div>
</asp:Content>
The code behind message view is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BAL;
using System.Data;
namespace SchoolMgmtSystem
{
public partial class MessageView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lvgetMessages.DataSource = null;
lvgetMessages.DataBind();
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
String userEmailId = AdminBizz.GetEmailId(userId, roleId);
DataTable dtMessageInfo = RoleBizz.GetUserMessages(userEmailId);
if (dtMessageInfo.Rows.Count > 0)
{
lvgetMessages.DataSource = dtMessageInfo;
lvgetMessages.DataBind();
}
}
protected void lvgetMessages_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
}
protected void ButtonBack_Click(object sender, EventArgs e)
{
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
Response.Redirect("MessageSend.aspx?UserId=" + userId + "&RoleId=" + roleId);
}
}
}
Here is the screen shot -

What you can probably do is get the NamingContainer of your delete button and find the other controls within it.
protected void ButtonDelete_Click(object sender, EventArgs e)
{
var control = (Control)sender;
var container = control.NamingContainer;
// access your controls this way
var emailIDLabel= container.FindControl("emailIDLabel") as Label;
var senderRoleLabel = container.FindControl("SenderRoleLabel") as Label;
var messageLabel = container.FindControl("MessageLabel") as Label;
}

You can do something like the answer for this question.
But remember to validate the value (with int.TryParse(string) for example).
<asp:Button ID="ButtonDelete" runat="server" Text="Delete"
OnClick="ButtonDelete_Click"
UseSubmitBehavior="False"
CommandName="Deleterecord"
CommandArgument='<%# Eval("[SenderEmailID]") %>'/>
protected void ButtonDelete_Click(object sender, EventArgs e)
{
int id;
var button = (Button)sender;
if(!int.TryParse(button.CommandArgument, out id))
{
// log.Write("possible sql injection");
return;
}
// do what you want
}

Related

ASP.NET C# WebForms ListView Highlight Item When Clicking

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

Getting values from the source page using "PreviousPage"

I’ve tried to post values between 2 web forms using the PreviousPage technique.
I have followed the MSDN article (http://msdn.microsoft.com/en-us/library/ms178139.aspx ) about the PreviousPage and I have referred this (http://www.deliciousdotnet.com/2011/03/getting-values-from-source-page-using.html#.Uw7jCvmSz3Q ) as well. All seem to be in order but I am seeing the following "Unknown member 'Designation' of System.Web.UI.Page" about my public methods in the destination page.
What have I done wrong?? Please help. Thank you.
this is my source pages html code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="adduser.aspx.cs" Inherits="adduser" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!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>
<link href="../Styles/main_style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body style="min-height: 600px; background-image: none !important;">
<form id="form1" runat="server">
<telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
<div class="lightboxContainer">
<div class="lightboxContainerSection">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table cellpadding="5" width="600px" class="style1" style="font-size: 12px; margin: 5px;
font-weight: bold;">
<tr>
<td>
Find User
</td>
<td>
<telerik:RadTextBox ID="RadTextBox1" runat="server" ValidationGroup="textbox1" OnTextChanged="TextBox1_TextChanged">
</telerik:RadTextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="RadTextBox1"
ErrorMessage="*" Style="color: #FF0000" ValidationGroup="textbox1"></asp:RequiredFieldValidator>
</td>
<td>
<telerik:RadButton ID="RadButton1" runat="server" Text="Find User" OnClick="RadButton1_Click"
ValidationGroup="textbox1">
</telerik:RadButton>
</td>
<td>
</td>
</tr>
<tr>
<td colspan="4">
<telerik:RadGrid ID="RadGrid_User" runat="server" OnNeedDataSource="RadGrid_User_NeedDataSource"
OnSelectedIndexChanged="RadGrid_User_SelectedIndexChanged" AllowPaging="True"
CellSpacing="0" GridLines="None">
<ClientSettings EnablePostBackOnRowClick="True">
<Selecting AllowRowSelect="True" />
</ClientSettings>
</telerik:RadGrid>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
User name
</td>
<td>
<asp:Label ID="LabelUser" runat="server" Text="Label"></asp:Label>
</td>
<td>
Company
</td>
<td>
<asp:Label ID="LabelCompany" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td>
Designation
</td>
<td>
<asp:Label ID="LabelDesignation" runat="server" Text="Label"></asp:Label>
</td>
<td>
Department
</td>
<td>
<asp:Label ID="LabelDepartment" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td>
Mobile
</td>
<td>
<asp:Label ID="LabelMobile" runat="server" Text="Label"></asp:Label>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td colspan="4">
<asp:Label ID="LabelConfirmation" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td>
<telerik:RadButton ID="RadButton2" runat="server" onclick="RadButton2_Click"
Text="Yes">
</telerik:RadButton>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<hr />
</div>
</form>
</body>
</html>
And this is my source page code behind file
using System;
using System.Linq;
using Telerik.Web.UI;
public partial class adduser : System.Web.UI.Page
{
private ActiveDirectory ad = new ActiveDirectory();
private DatabaseConnect db = new DatabaseConnect();
public void RadGrid_User_SelectedIndexChanged(object sender, EventArgs e)
{
GridDataItem selectedItem = (GridDataItem)RadGrid_User.SelectedItems[0];
string user = selectedItem["Email"].Text;
Session["userID"] = user.Split('#')[0];
RadTextBox1.Text = (string)Session["userID"];
string detail = ad.GetUserDetails(RadTextBox1.Text.Trim());
string[] details = detail.Split('/');
LabelUser.Text = details[0];
LabelCompany.Text = details[1];
LabelDepartment.Text = details[3];
LabelDesignation.Text = details[4];
LabelMobile.Text = details[5];
LabelConfirmation.Text = "Do you want to grant "+details[0]+" permission to access the CRI ?";
LabelUser.Visible = true;
LabelCompany.Visible = true;
LabelDepartment.Visible = true;
LabelDesignation.Visible = true;
LabelMobile.Visible = true;
LabelConfirmation.Visible = true;
RadButton2.Visible = true;
}
public void RadGrid_User_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
string username = this.RadTextBox1.Text.Trim();
if (username.Length >= 1)
{
this.RadGrid_User.DataSource = this.ad.GetUserDetails_WildCard(this.RadTextBox1.Text.Trim());
}
else
{
this.RadGrid_User.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (this.db.IsAllowedAdministrator(this.User.Identity.Name))
{
if (!this.IsPostBack)
{
LabelCompany.Visible = false;
LabelDepartment.Visible = false;
LabelDesignation.Visible = false;
LabelMobile.Visible = false;
LabelUser.Visible = false;
LabelConfirmation.Visible = false;
RadButton2.Visible = false;
}
}
else
{
this.Response.Redirect("~/ZCRI_RestrictedAdmin.aspx");
}
}
protected void RadButton1_Click(object sender, EventArgs e)
{
this.RadGrid_User.Rebind();
this.RadGrid_User.Visible = true;
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
LabelCompany.Visible = false;
LabelDepartment.Visible = false;
LabelDesignation.Visible = false;
LabelMobile.Visible = false;
LabelUser.Visible = false;
LabelConfirmation.Visible = false;
RadButton2.Visible = false;
}
public string Designation
{
get
{
return LabelDesignation.Text;
}
}
public string Mobile
{
get
{
return LabelMobile.Text;
}
}
public string Company
{
get
{
return LabelCompany.Text;
}
}
public string Department
{
get
{
return LabelDepartment.Text;
}
}
protected void RadButton2_Click(object sender, EventArgs e)
{
Response.Redirect(#"~/AdminInterfaces\adduserpermission.aspx");
}
}
This is my destination page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="adduserpermission.aspx.cs"
Inherits="adduserpermission" %>
<%# PreviousPageType VirtualPath="~/AdminInterfaces/adduser.aspx" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!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 id="Head1" runat="server">
<title></title>
<link href="../Styles/main_style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body style="min-height: 600px; background-image: none !important;">
<form id="form1" runat="server">
<telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
<div class="lightboxContainer">
<div class="lightboxContainerSection">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><asp:Label ID="Label2"
runat="server" Text="Label"></asp:Label><asp:Label ID="Label3"
runat="server" Text="Label"></asp:Label><asp:Label ID="Label4"
runat="server" Text="Label"></asp:Label>
</div>
</div>
</form>
</body>
</html>
My destination page code behind file
using System;
using System.Linq;
public partial class adduserpermission : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = PreviousPage.Designation;
Label2.Text = PreviousPage.Department;
Label3.Text = PreviousPage.Company;
Label4.Text = PreviousPage.Mobile;
}
}
Now this will work as i confused labels with your properties.
On previous Page you have a label with name LabelDesignation but here you are using wrong name to access it. try to use this.
You have an issue with this code in source page code behind file
this.Response.Redirect("~/ZCRI_RestrictedAdmin.aspx");
The PreviousPage property returns the page that sent control to this page using Server.Transfer.
If the current page is being rendered as a result of a direct request (not a transfer or cross-post from another page), the PreviousPage property contains null.
else
{
this.Server.Transfer("~/ZCRI_RestrictedAdmin.aspx");
}
using System;
using System.Linq;
public partial class adduserpermission : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.PreviousPage != null)
{
if(Page.PreviousPage.IsCrossPagePostBack == true)
{
Label1.Text = PreviousPage.Designation;
Label2.Text = PreviousPage.Department;
Label3.Text = PreviousPage.Company;
Label4.Text = PreviousPage.Mobile;
}
}
}
}
You need to cast it to right type:
public partial class adduserpermission : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
adduser prevPage = PreviousPage as adduser;
if (prevPage != null)
{
Label1.Text = prevPage.Designation;
Label2.Text = prevPage.Department;
Label3.Text = prevPage.Company;
Label4.Text = prevPage.Mobile;
}
}
}

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.

Repeater control checkbox event not fired

Am having three check box in repeater control. I need the concept like radio button list.When i click the first row first checkbox, other two are checked property is set to false. suppose i check the second one means first and third are unchecked.
My Design code is here :
<asp:Repeater ID="repeaterItems" runat="server"
onitemdatabound="repeaterItems_ItemDataBound" >
<ItemTemplate>
<table id="mytable" cellspacing="0" width="100%" align="center">
<tr>
<td style="width: 18px;">
<asp:Label ID="id" runat="server" Text='<%#Bind("fld_id")%>'></asp:Label>
</td>
<td style="width: 301px;">
<asp:Label ID="Label1" runat="server" Text='<%#Bind("fld_Question")%>'></asp:Label>
</td>
<td style="width: 10px;">
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
</td>
<td style="width: 30px;">
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox2_CheckedChanged"/>
</td>
<td style="width: 33px;">
<asp:CheckBox ID="CheckBox3" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox3_CheckedChanged"/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
code is :
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk1 = sender as CheckBox;
RepeaterItem item = chk1.Parent as RepeaterItem;
CheckBox chk2 = item.FindControl("CheckBox2") as CheckBox;
chk2.Checked = false;
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
}
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
}
protected void repeaterItems_ItemCreated1(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = (RepeaterItem)e.Item;
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem)
{
CheckBox chk = (CheckBox)e.Item.FindControl("CheckBox1");
chk.CheckedChanged += new EventHandler(CheckBox1_CheckedChanged);
}
}
CheckBox1_CheckedChanged event not fire. Please help me to fix this error.
I spent more time to solve this issue but i can't..
Just make sure that you are not binding the repeater on post back, and that viewstate is enabled on the repeater.
if(!Page.IsPostBack)
{
Repeater.Datasource = dataset(what ever source);
Repeater.Databind;
}
There is no reason why you should bind to the itemcreated event on the repeater, just to attach to the oncheckedchanged event, as this is pointless.
you can achieve by also JQuery
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('.chkGroup').change(function () {
var parentTr = $(this).parent().parent();
var currentCheckID = $(this).find('input').attr("id");
$(parentTr).find('.chkGroup input').each(function () {
if (currentCheckID != $(this).attr("id")) {
$(this).removeAttr("checked");
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="repeaterItems" runat="server" onitemdatabound="repeaterItems_ItemDataBound">
<ItemTemplate>
<table id="mytable" cellspacing="0" width="100%" align="center">
<tr>
<td style="width: 18px;">
<asp:Label ID="id" runat="server" Text='<%#Bind("ID")%>'></asp:Label>
</td>
<td style="width: 301px;">
<asp:Label ID="Label1" runat="server" Text='<%#Bind("Name")%>'></asp:Label>
</td>
<td style="width: 10px;">
<asp:CheckBox ID="CheckBox4" runat="server" CssClass="chkGroup" />
</td>
<td style="width: 30px;">
<asp:CheckBox ID="CheckBox5" runat="server" CssClass="chkGroup" />
</td>
<td style="width: 33px;">
<asp:CheckBox ID="CheckBox6" runat="server" CssClass="chkGroup" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
You can use the same event CheckBox1_CheckedChanged handler for all the three check-boxes OnCheckedChanged.
By using the sender object you could know which checkbox raised the event and then set the other two check-boxes checked property to false.

Show picture in 30 days ASP.NET

I am trying to make my first public .net website but I have a little problem.
It's a webshop, where i want to show at new product picture, if the product is not older than the current date with more than 30 days?
Markup:
<asp:Repeater ID="rptProducts" runat="server">
<ItemTemplate>
<table cellpadding="5" cellspacing="5" class="tblSales">
<tr>
<td>
<h3>
<asp:Label ID="Label1" Text='<%#Eval("ProductName")%>' runat="server" /></h3>
<h2>
<a href='<%# "Products.aspx?ID=" + Eval("ProductID") %>'>Read More</a></h2>
</td>
<td >
<h4>
<asp:Label ID="Label2" Text='<%#Eval("ProductPrice")%>' runat="server" />,-</h4>
<div>
<img alt="New product" src="images/NewProduct.png" /><!--This picture should show in 30 days-->
</div>
</td>
</tr>
<hr />
</table>
</ItemTemplate>
</asp:Repeater>
Code-behind:
public partial class sale : System.Web.UI.Page
{
ProductsTableAdapter p = new ProductsTableAdapter();
protected void Page_Load(object sender, EventArgs e)
{
GetData();
}
protected void GetData()
{
rptProducts = p.GetProductsByCategoryID(3);
rptProducts();
}
}
EDITED: As a user noted this may be a misinterpretation so...
IF you want to filter items that were added and not display them at all use the following LINQ expression on the GetData method:
rptProducts = p.GetProductsByCategoryID(3).Where(p=>p.ProductAddedDate > DateTime.Now.AddDays(-30));
you need to have a property (in the above example I added a DateTime ProductAddedDate to the product class
IF you want to not show the image based on the date BUT show everything else you could:
In the ItemDataBound event of the repeater you can set asp control (replace static html with asp:Image which allows you to control display using the Visible property i.e.
<asp:Repeater ID="rptProducts" runat="server" OnItemDataBound="rptProducts_Databound">
<ItemTemplate>
<table cellpadding="5" cellspacing="5" class="tblSales">
<tr>
<td>
<h3>
<asp:Label ID="Label1" Text='<%#Eval("ProductName")%>' runat="server" /></h3>
<h2>
<a href='<%# "Products.aspx?ID=" + Eval("ProductID") %>'>Read More</a></h2>
</td>
<td >
<h4>
<asp:Label ID="Label2" Text='<%#Eval("ProductPrice")%>' runat="server" />,-</h4>
<div>
<asp:Image ID="ProdImg" runat="server" AlternativeText="New product" ImageUrl='<%# "~/images/" + Eval("ImageFileName")' Visible="True"/><!--This picture should show in 30 days-->
</div>
</td>
</tr>
<hr />
</table>
</ItemTemplate>
</asp:Repeater>
CS codebehind
protected void rptProducts_Databound(object sender, RepeaterItemEventArgs e)
{
var imgCtrl = (Image)e.Item.FindControl("ProdImg");
var dataItem = (Product)e.Item.DataItem;
imCtrl.Visible = dataItem.ProductAddedDate > DateTime.Now.AddDays(-30);
}
Many thanks, I find out how to make it :)thanks to you, quite simple but i works.
here is the code I made:
<asp:Image ID="Image2" ImageUrl="~/images/new.png" Visible='<%#GetProductSalesPic(Eval("ProductDate"))%>' runat="server" />
C# code:
protected bool GetProductSalesPic(object Date)
{
DateTime actDate = (DateTime)Date;
if (DateTime.Now.AddDays(-30) < actDate)
{
return true;
}
else
{
return false;
}
}
And again, Thanks You, for the fast and good response :D

Categories