How to maintain DataList item index across Postbacks? - asp.net

I'm trying to retain the index of the Datalist item on page reload. I'm trying to do this by storing the index into a Session and then setting the index of DataList object equals to the Session. Here's the HTML code:
<asp:DataList ID="MyList" Width="100%" RepeatDirection="Vertical" runat="server"
OnItemDataBound="MyList_ItemDataBound" OnItemCommand="MyList_ItemCommand">
<ItemTemplate>
<table class="table">
<tr>
<td style="width: 5%;">
<asp:Label ID="lbl_id" runat="server" Text='<%# Eval("id") %>' Visible="false" />
<asp:Label ID="lbl_isread" runat="server" Text='<%# Eval("isread") %>' Visible="false" />
<input type="checkbox" id="chk_vd" runat="server" class="chkitem" />
</td>
<td style="width: 15%;">
<asp:HyperLink ID="usr" runat="server" Text='<%# Eval("from") %>' />
</td>
<td style="width: 62%;">
<asp:LinkButton ID="sub" Text='<%# Eval("subject") %>' CommandName="select" runat="server"></asp:LinkButton>
</td>
<td style="width: 18%;">
<asp:Label ID="dt" runat="server" Text='<%# Eval("Date_Added") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SelectedItemTemplate>
<table class="table">
<tr>
<td style="width: 5%;">
<asp:Label ID="lbl_id" runat="server" Text='<%# Eval("id") %>' Visible="false" />
<asp:Label ID="lbl_isread" runat="server" Text='<%# Eval("isread") %>' Visible="false" />
<asp:Label ID="lbl_messagetype" runat="server" Text='<%# Eval("messagetype") %>'
Visible="false" />
<asp:Label ID="lbl_groupid" runat="server" Text='<%# Eval("groupid") %>' Visible="false" />
<asp:Label ID="lbl_content_id" runat="server" Text='<%# Eval("content_id") %>' Visible="false" />
<asp:Label ID="lbl_sendertype" runat="server" Text='<%# Eval("sendertype") %>' Visible="false" />
<input type="checkbox" id="chk_vd" runat="server" class="chkitem" />
</td>
<td style="padding: 5px; text-align: left; vertical-align: top; width: 15%;">
<uc1:avator ID="avt" runat="server" UserName='<%# Eval("from") %>' PhotoName="" Width="65"
Height="65" />
<br />
<asp:HyperLink ID="usr" runat="server" Text='<%# Eval("from") %>' />
</td>
<td style="padding: 5px; text-align: left; vertical-align: top; width: 62%;">
<div class="item_pad_4">
<h3 id="s_sub" runat="server">
<%# Eval("subject") %>
</h3>
</div>
<asp:Label ID="msg" runat="server" Text='<%# Eval("body") %>'></asp:Label>
<div class="bx_br_tp item_pad_4">
<div class="btn-group" id="<%# Eval("id") %>">
<asp:LinkButton ID="a" CssClass="btn btn-primary btn-xs" runat="server" />
<asp:LinkButton ID="r" CssClass="btn btn-primary btn-xs" runat="server" />
<%-- <asp:LinkButton ID="lnk_spam" CssClass="btn btn-primary btn-xs" runat="server"
Text="spam" CommandName="spam"></asp:LinkButton>--%>
</div>
</div>
</td>
<td style="padding: 5px; text-align: left; vertical-align: top; width: 18%;">
<asp:Label ID="dt" runat="server" Text='<%# Eval("Date_Added") %>' />
</td>
</tr>
</table>
</SelectedItemTemplate>
</asp:DataList>
On the server side, I'm trying to restore the index of the DataList item as follows:
if (!Page.IsPostBack)
{
if (Session["datalist"] != null)
{
((DataList)Session["datalist"]).SelectedIndex = (int)Session["index"];
}
Here's the function which does data binding :
protected void MyList_ItemCommand(object source, DataListCommandEventArgs e)
{
Session["datalist"] = source;
string cmd = ((LinkButton)e.CommandSource).CommandName;
long messageid = long.Parse(((Label)e.Item.FindControl("lbl_id")).Text);
string username = ((HyperLink)e.Item.FindControl("usr")).Text;
// approve / ignore action related values
long content_id = 0;
long groupid = 0;
int messagetype = 0;
int index = e.Item.ItemIndex;
Session["index"] = index;
index = (int)Session["index"];
switch (cmd)
{
case "select":
((DataList)source).SelectedIndex = e.Item.ItemIndex;
int isread = int.Parse(((Label)e.Item.FindControl("lbl_isread")).Text);
// mark message as read it its unread message
if (isread == 0)
{
isread = 1; // message is read
MailBoxBLL.Update_isRead(messageid, isread, Page.User.Identity.Name);
}
string _cache = "usr_msg_cnt_" + UserName;
if (HttpContext.Current.Cache[_cache] != null)
{
Cache.Remove(_cache);
}
break;
This doesn't work and Datalist item does not get selected when the page reloads. How can I make it work?
Any help is appreciated.

Add this directly in Page Load:-
protected void Page_Load(object sender, EventArgs e)
{
if (Session["datalist"] != null)
((DataList)Session["datalist"]).SelectedIndex = (int)Session["index"];
}
The probelm with your code is that the Page.IsPostBack property will be false in the initial get request and for every page reload (actual postback) it will be true. Thus !Page.IsPostBack will become actually false and your code will never execute.

Related

asp.net gridview - spread bound data across multi lines per row with updatepanel

I have a panel inside a gridview and I need it to be 'spread' for the width of the row :
never mind what's in the panel. What I show here is just to demo my needs...My HTML:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
CellPadding="3"
CssClass="myGrid"
DataKeyNames="Role_Name">
<AlternatingRowStyle BackColor="#E6E6E6" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShow" runat="server" OnClick="Show_Hide_details" BorderStyle="None" BackColor="Transparent" ImageUrl="~/Content/Images/Arrow_Down.png"
CommandArgument="Show" />
<asp:Panel ID="pnlRole" runat="server" Style="position: relative;" Visible="false">
<asp:Label ID="lblAAA" runat="server" Text="aaa" /><br />
<asp:Label ID="lblBBB" runat="server" Text="bbb" /><br />
<asp:Label ID="lblCCC" runat="server" Text="ccc" /><br />
<asp:Label ID="lblDDD" runat="server" Text="ddd" /><br />
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Role_Name" HeaderText="Name">
<HeaderStyle Width="100px" />
<ItemStyle CssClass="myGridItemMaxWidth" HorizontalAlign="Left" Wrap="false" />
</asp:BoundField>
<asp:BoundField DataField="Role_Description" HeaderText="Description">
<HeaderStyle Width="150px" />
<ItemStyle CssClass="myGridItemMaxWidth" HorizontalAlign="Left" Wrap="false" />
</asp:BoundField>
</Columns>
<HeaderStyle CssClass="myGridHeader" />
<RowStyle ForeColor="#000066" />
</asp:GridView>
I'd appreciate any help/idea/solution.
EDIT :
To better explain my problem, here's another image :
(never mind what's in the panel. What I show here is just to demo my needs...)
It's tough to do that properly inside of a GridView without it becoming unwieldy.
You would better off with a ListView and using the functionality there.
<asp:ListView ID="ListView1" runat="server"
DataKeyNames="Role_Name"
OnItemCommand="ListView1_ItemCommand">
<LayoutTemplate>
<table class="myGrid">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Description</th>
</tr>
</theah>
<tbody>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:ImageButton ID="imgShow" runat="server" BorderStyle="None" BackColor="Transparent" ImageUrl="~/Content/Images/Arrow_Down.png" CommandName="Toggle" />
</td>
<td><%# Eval("Role_Name") %></td>
<td><%# Eval("Role_Description") %></td>
</tr>
<tr>
<td colspan="3">
<asp:Panel ID="pnlRole" runat="server" Style="position: relative;" Visible="false">
<asp:Label ID="lblAAA" runat="server" Text="aaa" /><br />
<asp:Label ID="lblBBB" runat="server" Text="bbb" /><br />
<asp:Label ID="lblCCC" runat="server" Text="ccc" /><br />
<asp:Label ID="lblDDD" runat="server" Text="ddd" /><br />
</asp:Panel>
</td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<p>No data found.</p>
</EmptyDataTemplate>
</asp:ListView>
This will unfortunately have an extra <tr>...</tr> for each row. To resolve that, a way you could do this is to use runat="server" for the <tr> in place of the Panel.
<tr id="pnlRole" runat="server" Visible="false">
<td colspan="3">
<asp:Label ID="lblAAA" runat="server" Text="aaa" /><br />
<asp:Label ID="lblBBB" runat="server" Text="bbb" /><br />
<asp:Label ID="lblCCC" runat="server" Text="ccc" /><br />
<asp:Label ID="lblDDD" runat="server" Text="ddd" /><br />
</td>
</tr>
Now in the code-behind you can reference this
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Toggle")
{
HtmlTableRow pnlRole = e.Item.FindControl("pnlRole") as HtmlTableRow;
pnlRole.Visible = !pnlRole.Visible;
ImageButton imgShow = e.Item.FindControl("imgShow") as ImageButton;
if (pnlRole.Visible == true)
imgShow.ImageUrl="~/Content/Images/Arrow_Down.png";
else
imgShow.ImageUrl="~/Content/Images/Arrow_Up.png";
}
}
Here is what I came up with -
On the left is the GridView when all rows are 'closed'. On the right, after 'opening' 2 rows:
Markup:
<form id="form1" runat="server" style="">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<table runat="server" style="font-weight: bold; margin: 0 auto; font-family: Arial;">
<tr>
<td style="text-align: center; width: 500px; overflow: hidden">
<asp:GridView ID="grv_Four_Rows" runat="server"
AutoGenerateColumns="False" BackColor="black" GridLines="None"
CellPadding="3" CssClass="myGrid" DataKeyNames="Test1_First_Name">
<HeaderStyle CssClass="myGridHeader" />
<RowStyle BackColor="#b5c7de" />
<AlternatingRowStyle BackColor="#d1e0e0" />
<Columns>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Left" />
<HeaderTemplate>
<table>
<tr>
<td style="width: 150px;">First</td>
<td style="width: 150px;">Last</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table>
<td>
<asp:UpdatePanel ID="upp_Main_Row" runat="server">
<ContentTemplate>
<asp:Panel runat="server">
<td>
<asp:ImageButton ID="imgShow" runat="server" OnClick="Show_Hide_details"
ImageUrl="~/Content/Images/Arrow_Down.png" CommandArgument="Show" />
</td>
<td style="width: 150px"><%# Eval("Test1_First_Name")%></td>
<td style="width: 150px"><%# Eval("Test1_Last_Name")%></td>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</table>
<table style="border-style: solid; border-width: thin; width: 100%">
<asp:UpdatePanel ID="upp_2nd_row" runat="server" Visible="false">
<ContentTemplate>
<tr>
<td>
<a style="color: red">Address: </a><%# Eval("Test1_Address")%>
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="upp_3rd_row" runat="server" Visible="false">
<ContentTemplate>
<tr>
<td>
<a style="color: red;">Description: </a><%#Eval("Test1_Description")%>
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="upp_4th_row" runat="server" Visible="false">
<ContentTemplate>
<tr style="float: left">
<td>
<a style="color: red">Note1: </a><%#Eval("Test1_Note_1")%>
<a style="color: red">Note2: </a><%#Eval("Test1_Note_2")%>
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</form>
<style type="text/css">
.myGrid {
border: 1px solid black;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
overflow: hidden;
background-color: white;
text-align: center;
margin: 0 auto;
}
.myGridHeader > th {
text-align: center;
border: solid 1px;
font-family: Arial;
background-color: #DDFFD6;
font-weight: bold;
color: #000066;
}
</style>
C# code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
load_grv_Four_Rows();
}
}
//================================================================================================
protected void Show_Hide_details(object sender, EventArgs e)
{
ImageButton imgShowHide = sender as ImageButton;
GridViewRow row = imgShowHide.NamingContainer as GridViewRow;
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("upp_2nd_Row").Visible = true;
row.FindControl("upp_3rd_Row").Visible = true;
row.FindControl("upp_4th_Row").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/Content/Images/Arrow_Up.png";
}
else
{
row.FindControl("upp_2nd_Row").Visible = false;
row.FindControl("upp_3rd_Row").Visible = false;
row.FindControl("upp_4th_Row").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/Content/Images/Arrow_Down.png";
}
}
//================================================================================================
private void load_grv_Four_Rows()
{
try
{
SqlConnection con;
DataSet ds;
con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BETSEFER_DB"].ConnectionString);
string CmdString = "SELECT * FROM tbl_Test1 ORDER BY Test1_First_Name";
ds = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(CmdString, con))
{
sda.Fill(ds);
if (ds.Tables.Count > 0)
{
DataView dv = ds.Tables[0].DefaultView;
grv_Four_Rows.DataSource = dv;
grv_Four_Rows.DataBind();
}
}
}
catch (SqlException ex)
{
Session["mySQL_Error_Msg"] = ex.Message;
Server.ClearError();
Response.Redirect("~/Errors.aspx");
}
}
//================================================================================================
The table:
I still have lots of formatting and cosmetic issues but for those I'll open a new post.
Hope it helps someone.

ImageButton Visibility not getting changed in aspx.cs page

I'm using a gridview to display some data. There is an image button to display a flag. Within the GridView RowDataBound Event i'm changing the visibility of that button. But the visibility didn't get changed. Here is the code:
bool status = true; // getting this via dataset
ImageButton imgTest = (ImageButton)e.Row.FindControl("ImageButton1");
imgTest.Visible = status;
But still visibility is false.
EDIT:
Here is my HTML Code;
<asp:GridView runat="server" ID="gvScheduleView" DataKeyNames="ControlID,IsPrinted, PrintDate, DueDate"
Width="100%" ShowHeader="true" ShowFooter="true" AutoGenerateColumns="false"
OnRowDataBound="gvScheduleView_rowDataBound" Height="100%" CssClass="removePaddingRight">
<Columns>
<asp:TemplateField HeaderText="Type" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Eval("Type") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="120">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Actions" HeaderStyle-HorizontalAlign="Center"
ItemStyle-Width="150" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<div style="text-align: center;">
<table style="margin-left: 28px;">
<tr style="text-align: center;">
<td style="width: 20px">
<asp:ImageButton ID="ibDelete" runat="server" ImageUrl="~/common/images/delete.gif"
OnClick="ibDelete_click" OnClientClick="return confirm('Are you sure you wish to delete this schedule?');"
CommandArgument='<%# Eval("ControlID") %>' ToolTip="Delete Schedule" />
</td>
<td style="width: 20px">
<asp:ImageButton ID="ibRollback" runat="server" ImageUrl="~/common/images/icons/arrow_undo.png"
OnClick="ibRollback_click" CommandArgument='<%# Eval("ControlID") %>' ToolTip="Rollback print generation"
OnClientClick="return confirm('Are you sure you wish to rollback this schedule?');" />
</td>
<td style="width: 20px">
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/common/images/icons/email_go.png"
OnClick="ibGenerate_click" CommandArgument='<%# Eval("ControlID") %>' />
<asp:Image ImageUrl="~/common/images/icons/cancel.png" ID="imInfo" runat="server"
Visible="false" ToolTip="DUE DATE IS INVALID - Please change to a future date" />
</td>
<td style="width: 20px">
<asp:ImageButton ID="ibEditProps" runat="server" ImageUrl="~/common/images/icons/building_edit.png"
OnClick="ibEditProps_click" CommandArgument='<%# Eval("ControlID") %>' CommandName='<%# Eval("Type") %>'
ToolTip="Edit Properties" />
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div id="DivBtnImgCopy" runat="server" visible = "<% =ShowHideButton() %>">
<asp:ImageButton ID="ibEditProps" runat="server"ImageUrl="~/common/images/icons/building_edit.png"
OnClick="ibEditProps_click"CommandArgument='<%# Eval("ControlID") %>' CommandName='<%# Eval("Type") %>' ToolTip="Edit Properties" />
</div>
Code Behind
protected bool ShowHideButton()
{
bool bStatus = false;
try
{
if (sCondition == "false")
{
bStatus = false;
}
else if (sCondition == "true")
{
bStatus = true;
}
return bStatus;
}
catch { }
}

Paging data from access with SEO friendly urls

I need some help about how to paging data from access data base.
I used asp:ListView and asp:DataPager like some example I found but the paging work with javascript and I want the paging will be friendly.
How I can put some of my code?
[edit]
this is the code:
<asp:ListView ID="tblProjects" runat="server" OnPagePropertiesChanging="tblProjects_PagePropertiesChanging">
<LayoutTemplate>
<ul class="ulProducts">
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<div class="divProduct">
<a rel='pics' href='GalleryEditor/pictures/<%# Eval("BigImageName") %>'>
<img src='GalleryEditor/pictures/<%# Eval("SmallImagesName") %>'
alt='<%# Eval("ImageDetail") %>' title='<%# Eval("ImageDetail") %>' />
</a>
</div>
</li>
</ItemTemplate>
<EmptyDataTemplate>
no data
</EmptyDataTemplate>
This the code behind:
protected void tblProjects_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
//set current page startindex, max rows and rebind to false
imagesPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
string page = Request.QueryString["p"];
if (!(FormValidator.IsNumber(page)))
page = "8800";
buildProducts(page);
}
void buildTitleAndDescription(string page)
{
// set page title
OleDbConnection conn0 = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" + Server.MapPath("GalleryEditor\\App_Data\\projects.mdb"));
OleDbCommand comm0 = new OleDbCommand("select ProjectName from Project where PlaceID=" + page, conn0);
OleDbDataReader reader0;
conn0.Open();
reader0 = comm0.ExecuteReader();
reader0.Read();
Page.Header.Title = reader0["ProjectName"].ToString();
reader0.Close();
conn0.Close();
//if (IsPostBack)
//{
// string Script = "<script type='text/javascript'>goToEnd();\n</script>";
// Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", Script);
//}
}
void buildProducts(string page)
{
// set page content
OleDbConnection conn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" + Server.MapPath("GalleryEditor\\App_Data\\sb.mdb"));
OleDbCommand comm = new OleDbCommand("select SmallImagesName, BigImageName, ImageDetail from Images where PlaceID=" + page, conn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(comm);
da.Fill(ds);
tblProjects.DataSource = ds;
tblProjects.DataBind();
}
I do not mind change the code to better one and if I learn form it I will appreciate it.
All the example I found is for SQL and my data need to be on access.
Here is an example of asp listview you will have to define the querystring as follows.
<asp:ListView ID="ListView1" runat="server" DataKeyNames="bd_book_code"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<AlternatingItemTemplate>
<tr style="">
<td>
<asp:Label ID="bd_book_codeLabel" runat="server"
Text='<%# Eval("bd_book_code") %>' />
</td>
<td>
<asp:Label ID="bd_isbnLabel" runat="server" Text='<%# Eval("bd_isbn") %>' />
</td>
<td>
<asp:Label ID="bd_titleLabel" runat="server" Text='<%# Eval("bd_title") %>' />
</td>
</tr>
</AlternatingItemTemplate>
<EditItemTemplate>
<tr style="">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update"
Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Cancel" />
</td>
<td>
<asp:Label ID="bd_book_codeLabel1" runat="server"
Text='<%# Eval("bd_book_code") %>' />
</td>
<td>
<asp:TextBox ID="bd_isbnTextBox" runat="server" Text='<%# Bind("bd_isbn") %>' />
</td>
<td>
<asp:TextBox ID="bd_titleTextBox" runat="server"
Text='<%# Bind("bd_title") %>' />
</td>
</tr>
</EditItemTemplate>
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>
No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<InsertItemTemplate>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" />
</td>
<td>
<asp:TextBox ID="bd_book_codeTextBox" runat="server"
Text='<%# Bind("bd_book_code") %>' />
</td>
<td>
<asp:TextBox ID="bd_isbnTextBox" runat="server" Text='<%# Bind("bd_isbn") %>' />
</td>
<td>
<asp:TextBox ID="bd_titleTextBox" runat="server"
Text='<%# Bind("bd_title") %>' />
</td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:Label ID="bd_book_codeLabel" runat="server"
Text='<%# Eval("bd_book_code") %>' />
</td>
<td>
<asp:Label ID="bd_isbnLabel" runat="server" Text='<%# Eval("bd_isbn") %>' />
</td>
<td>
<asp:Label ID="bd_titleLabel" runat="server" Text='<%# Eval("bd_title") %>' />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table ID="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">
bd_book_code</th>
<th runat="server">
bd_isbn</th>
<th runat="server">
bd_title</th>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server" QueryStringField="pid">
<Fields>
<asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="False" />
<asp:NumericPagerField />
<asp:NextPreviousPagerField ButtonType="Link" ShowLastPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="False" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<tr style="">
<td>
<asp:Label ID="bd_book_codeLabel" runat="server"
Text='<%# Eval("bd_book_code") %>' />
</td>
<td>
<asp:Label ID="bd_isbnLabel" runat="server" Text='<%# Eval("bd_isbn") %>' />
</td>
<td>
<asp:Label ID="bd_titleLabel" runat="server" Text='<%# Eval("bd_title") %>' />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
QueryStringField="pid" will do the magic.

How to use javascript validations for controls within ListView EditTemplate?

In Nridubai website,i am using listview EditTemplate for editing purpose. In my EditTemplate, there are controls like..
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
And a few more controls like dropdownlist, calender controls. Now I want to validate using javascript on these controls, but its not working.
Eg.
var eventStatus=document.getElementById("<%=txtEditEventName.ClientID%>").value;
I am not using validation controls. Please help me how to use javascript for validation on EditTemplate Controls? My EditTemplate structure is like the following:
<EditItemTemplate>
<td class="command"><asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
<asp:LinkButton ID="LinkButton2" runat="server" Text="Update" CommandName="Update" />
</td>
<div class="header">View Details for '<%# Eval("event_name")%>'</div>
<tr>
<td class="edit" colspan="6" >
<div class="details">
<table class="detailview" cellpadding="0" cellspacing="0">
<tr>
<td>Event Name:</td>
<td>
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
</td>
<td>VenueAddress :</td>
<td>
<asp:TextBox ID="txtEditVenue" runat="server" Text='<%# Bind("venue") %>' />
</td>
</tr>
<tr>
<td>Country :</td>
<td>
<asp:DropDownList ID="lstEditCountry" runat="server"
Width="174" />
</td>
<td>Event Status:</td>
<td>
<asp:DropDownList ID="lstEditStatus" runat="server" Width="175px" >
<asp:ListItem value='0' Selected="True">-Select-</asp:ListItem>
<asp:ListItem >In-Progress</asp:ListItem>
<asp:ListItem >Completed</asp:ListItem>
<asp:ListItem >Aborted</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Category :</td>
<td>
<asp:DropDownList ID="lstEditCategory" runat="server"
Width="174" />
</td>
</tr>
<tr>
<td>Start Date:</td>
<td>
<asp:TextBox ID="txtEditStartDate" runat="server"
Text='<%# Bind("start_date", "{0:dd/MM/yyyy}") %>' />
</td>
<td>End Date:</td>
<td>
<asp:TextBox ID="txtEditEndDate" runat="server"
Text='<%# Bind("end_date","{0:dd/MM/yyyy}") %>' />
</td>
</tr>
</table>
<div class="footer command">
<asp:LinkButton ID="LinkButton1" runat="server" Text="Close" CommandName="Cancel" />
</div>
</div>
</td>
</tr>
</EditItemTemplate>
You can access the elements on ItemDataBound and emit their ClientIDs for your JavaScript to use:
ItemDataBound:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
StringBuilder vars= new StringBuilder();
if (ListView1.EditItem != null)
{
TextBox txtEditStartDate = ListView1.EditItem.FindControl("txtEditStartDate") as TextBox;
TextBox txtEditEndDate = ListView1.EditItem.FindControl("txtEditEndDate") as TextBox;
//example js, however I recommend passing the ClientIDs to functions
vars.Append(String.Format("var txtEditStartDate='{0}';" txtEditStartDate.ClientID);
vars.Append(String.Format("var txtEditStartDate='{0}';", txtEditEndDate.ClientID );
ClientScriptManager.RegisterStartUpScript(this.GetType(), "validationVars", vars.ToString(), true);
}
}
***Old Answer, the .NET way************
EditTemplate:
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
<asp:RequiredFieldValidator
id="rfvEditEventName"
ClientValidationFunction="txtEditEventNameClientValidate"
ControlToValidate="txtTitle"
runat="server"
Display="dynamic">*
</asp:RequiredFieldValidator>
JS:
function txtEditEventNameClientValidate(sender, args) {
if (args.Value == '') {
args.IsValid = false; // field is empty
//so something
}
else {
//do something
}
}
Put the validation javascript in the EditTemplate itself. This way, when it switches to edit-mode, the control will be in the context.

how to find the control OfferID?

<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1"
DataKeyNames="OfferID" GroupItemCount="2" >
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table ID="groupPlaceholderContainer" runat="server" border="0" style="">
<tr ID="groupPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<td runat="server" style="">
<div id="wrapper">
<div id="ResImage">
<div id="slideshow">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval ("Image1") %>' Width="250px" Height="190px" CssClass="active" />
<asp:Image ID="Image5" runat="server" ImageUrl='<%# Eval ("Image2") %>' Width="250px" Height="190px" />
<asp:Image ID="Image4" runat="server" ImageUrl='<%# Eval ("Image3") %>' Width="250px" Height="190px" />
</div>
</div>
<div id="ResDesc">
<asp:Label ID="lblDesc" runat="server" Width="290px" Height="190px" BackColor="White" Text='<%# Eval("Offer") %>'></asp:Label>
</div>
<div id="ResPrice1">
<asp:Label ID="lblValue" runat="server" Text="Value" CssClass="ResValue"></asp:Label>
<asp:Label ID="lblDiscount" runat="server" Text="Discount" CssClass="ResDiscount"></asp:Label>
<asp:Label ID="lblYouPay" runat="server" Text="You Pay" CssClass="ResYouPay"></asp:Label>
<div id="ResPrice2">
<asp:Label ID="lblValueAmt" runat="server" Text='<%# Eval("Value") %>' CssClass="ResValueAmt"></asp:Label>
<asp:Label ID="lblDiscountAmt" runat="server" Text='<%# Eval("Discount") %>' CssClass="ResDiscountAmt"></asp:Label>
<asp:Label ID="lblYouPayAmt" runat="server" Text='<%# Eval("YouPay") %>' CssClass="ResYouPayAmt"></asp:Label>
</div>
<asp:Label ID="lblRestaurantName" runat="server" Text='<%# Eval("RestaurantName") %>'></asp:Label><br />
<asp:LinkButton ID="lnkGetCoupon" runat="server">Get Discount Coupon</asp:LinkButton>
</div>
<div id="HowItWorks">
<asp:Label ID="lblHowItWorks" runat="server" Text="How It Works?" Font-Bold="True" Font-Size="Small" ForeColor="Red"></asp:Label>
<ul>
<li><asp:Label ID="Label3" runat="server" Text="1.Click on the 'Get Discount Coupon' button" Font-Size="10px"></asp:Label></li>
<li><asp:Label ID="Label4" runat="server" Text="2.Get a print of your Voucher and carry it during your visit to the outlet." Font-Size="10px"></asp:Label></li>
<li><asp:Label ID="Label5" runat="server" Text="3.Show your Voucher and pay the amount directly to the merchant. " Font-Size="10px"></asp:Label></li>
</ul>
</div>
<asp:Label ID="OfferID" runat="server" Text='<%# Eval("OfferID") %>' Visible="false"></asp:Label>
</div>
</td>
</ItemTemplate>
How to find the label control with the id=OfferID...how to use findcontrol here??
i want to find the OfferID of the row on which i click...i have a linkbutton lnkGetCoupon..when i click on the link button...i want to pass the OfferID in the query string to the next page.
i am a new user so they do not let me post answer to my own question
heres the answer...
i added CommandArgument='<%# Eval("OfferID") %> to the link button.
<asp:LinkButton ID="lnkGetCoupon" CommandArgument='<%# Eval("OfferID") %>' runat="server">Get Discount Coupon</asp:LinkButton>
and used the ListView1_ItemCommand
Protected Sub ListView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ListView1.ItemCommand
Dim offer As String
offer = e.CommandArgument.ToString()
Dim url As String = "~/RestaurantDedicatedPage.aspx?offerID=" + offer
Response.Redirect(url, True)
End Sub
You don't need the Label at all, you can get the OfferID from the DataKeys collection.
First, add a CommandName to your LinkButton:
<asp:LinkButton ID="lnkGetCoupon" runat="server" CommandName="GetCoupon">Get Discount Coupon</asp:LinkButton>
Then use it in the ItemCommand handler:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "GetCoupon")
{
ListViewDataItem item = (ListViewDataItem)e.Item;
int index = item.DataItemIndex;
string offerID = ((ListView)sender).DataKeys[index]["OfferID"].ToString();
Response.Redirect("yourUrl" + offerID);
}
}
Attach to the ListView.ItemCommand event and within that event you can search on the Item in the ListViewCommandEventArgs to find the control you need to alter.
Update your ListView in your ASPX to hook up the ItemCommand event:
<asp:ListView ... OnItemDataBound="ListView1_ItemCommand">
<ItemTemplate>
...
<asp:LinkButton id="lnkGetCoupon" CommandName="View" CommandArgument="<%# Eval("OfferID") %>" />
...
</ItemTemplate>
</asp:ListView>
The ItemCommand event will be fired when a Button or LinkButton (or some other button-esque control) is clicked. To handle this event, add the following
code to your *.aspx.cs (code-behind) file:
protected void ListView1_ItemDataBound(object sender, ListViewCommandEventArgs e)
{
//Check if the lnkGetCoupon button was clicked.
if (string.Equals("View", e.CommandName))
{
//Get the offerID from the CommandArgument.
int offerID = int.Parse(e.CommandArgument);
//Perform your logic using the offerID
}
}

Resources