Create a dropdown that filters the output of my repeater - asp.net

I have a repeater that lists all the products in my Products table and I need a dropdown box to filter the repeater content by category_id. I have absolutely no idea what I'm doing. Here is my repeater:
<asp:Repeater ID="RShopItems" runat="server" ItemType="WebDevAssessment.Models.Product">
<ItemTemplate>
<div class="col-md-4 productOuterContainer">
<div class="col-md-10 col-md-offset-1 productInnerContainer border">
<a href='<%#"ProductDetails.aspx?item=" + Item.product_id %>' runat="server" target="_parent">
<img runat="server" alt='<%# Item.product_name %>' src='<%# Item.product_image1 %>'
style="width: 100%" class="img-thumbnail" />
</a>
<h4 class="text-center"><%# Item.product_name %></h4>
<p class="text-center">Size: <%#Item.product_size%> - $<%#Item.product_price%></p>
<p class="features_text text-center"><%#Item.product_feat_short%></p>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And the behind code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebDevAssessment.Models;
namespace WebDevAssessment
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (WebDatabaseEntities wde = new WebDatabaseEntities())
{
var products = (from si in wde.Products
orderby si.product_price descending
select si).ToList();
// assign the data to the repeater
RShopItems.DataSource = products;
// trigger the repeater to incorporate to display the data
RShopItems.DataBind();
}
}
}
}

Ok, you can use this apporach.
In this example, we have a repeater - showing hotel names.
We have a drop down list to filter by city (no choice = all cities).
So, the mark up looks like this:
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="City" DataValueField="ID" AutoPostBack="True">
</asp:DropDownList>
<br />
<br />
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px;float:left">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' Width="130px" />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
City: <asp:TextBox ID="txtCity" runat="server" Text ='<%# Eval("City") %>' Width="130px" />
<br />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And the code to load up drop, load up Repeater, and filter looks like this:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
LoadDropDown();
LoadGrid();
}
}
public void LoadDropDown()
{
// load drop down list
using (SqlCommand cmdSQL = new SqlCommand("SELECT ID, City from tblCity ORDER BY City",
new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
DropDownList1.DataSource = cmdSQL.ExecuteReader;
DropDownList1.DataBind();
// add blank row choice to drop down list
DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
}
}
public void LoadGrid(string sFilter = "")
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels",
new SqlConnection(My.Settings.TEST3)))
{
if (sFilter != "")
{
cmdSQL.CommandText += " WHERE City = #City";
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = DropDownList1.SelectedItem.Text;
}
cmdSQL.CommandText += " ORDER BY HotelName";
cmdSQL.Connection.Open();
Repeater1.DataSource = cmdSQL.ExecuteReader;
Repeater1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LoadGrid(DropDownList1.SelectedItem.Text);
}
So it now looks like this:
So, on first load - you load up the dropdown, and the repeater.
Dropdown list has auto post back = true, and it simply filters the Repeater by applying a parameters (optional) to the data source for the repeater.
It not a lot of code, and I don't see any advantages to using linq as you are.

Related

ASP.NET repeater dynamic value

I try to use a repeater in repeater in ASP.NET, but I want to change datasource from every repeat.
My aspx markup is:
<div class="container px-4 py-5" id="custom-cards">
<asp:Repeater ID="RepeaterKategori" runat="server" OnItemDataBound="ItemBound">
<ItemTemplate>
<h2 class="pb-2 border-bottom"><%#Eval("kategoriAd") %></h2>
<div class="row row-cols-1 row-cols-md-3 g-4">
<asp:Repeater ID="RepeaterAltKategori" runat="server">
<ItemTemplate>
<div class="col">
<div class="card h-100">
<img src="<%#Eval("altkategoriResim") %>" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title"><%#Eval("altkategoriBaslik") %></h5>
<p class="card-text"><%#Eval("altkategoriAciklama") %></p>
</div>
<div class="card-footer">
<small class="text-muted">Teşekkürler : <%#Eval("altkategoriDestekci") %></small>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="d-grid gap-2 my-4">
Tümünü Görüntüle
</div>
</ItemTemplate>
</asp:Repeater>
</div>
My aspx.cs code behind is:
rehber kod = new rehber();
protected void Page_Load(object sender, EventArgs e)
{
RepeaterKategori.DataSource = kod.getDataTable("SELECT KategoriAd FROM kategoriler");
RepeaterKategori.DataBind();
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
DataTable katsay = kod.getDataTable("SELECT * FROM altkategoriler");
int kategoris = katsay.Rows.Count;
for (int i = 1; i == kategoris; i++)
{
Repeater RepeaterAltKategori = (Repeater)args.Item.FindControl("RepeaterAltKategori");
RepeaterAltKategori.DataSource = kod.getDataTable("SELECT TOP 3 * FROM altkategoriler WHERE kategoriId="+i+"");
RepeaterAltKategori.DataBind();
}
}
}
I want another id data like 1,2,3,4 for every repeat. How can I do this? Thanks..
You need to nest two repeaters then.
You have
top table - feed the main repeater - 1 record for each.
child table - feed the child repeater - child table - many records for each.
Also, make sure you ALWAYS use if (!isPostBack) to have a real first page load - if you don't do most (if not all) of your loading and databinding inside of the !IsPostback?
you cannot even really quite much build a working page that can survive post-backs.
Ok, so we have the master (top) repeater.
for the child repeater, you might have one record, maybe many. It don't matter. But WHAT DOES matter is you now have a whole new seperate data set and whole new set of Eval() and binding that belongs to that child table or child data set.
So, lets take a main repeater (our hotels), and for each instance, we drop in another repeater to display the child data (in this case people booked in the hotel).
So, we have this mark-up - note the nested 2nd repeater.
<asp:Repeater ID="repHotels" runat="server" OnItemDataBound="repHotels_ItemDataBound">
<ItemTemplate>
<asp:Label ID="txtHotel" runat="server" Width="240px"
Text='<%# Eval("HotelName") %>' Font-Size="X-Large" >
</asp:Label>
<asp:TextBox ID="txtDescription" runat="server"
Text='<%# Eval("Description") %>'
TextMode="MultiLine" Rows="5" Columns="40" Style="margin-left:20px" >
</asp:TextBox>
<br />
<h4>People Booked</h4>
<asp:Repeater ID="repPeopleBooked" runat="server">
<ItemTemplate>
<asp:Label ID="lFirst" runat="server" Text='<%# Eval("FirstName") %>'>
</asp:Label>
<asp:Label ID="lLast" runat="server" Text='<%# Eval("LastName") %>'
style="margin-left:10px">
</asp:Label>
<br />
</ItemTemplate>
</asp:Repeater>
<%-- our repeat separator --%>
<div style="height:20px">
<hr style="border:1px solid" />
</div>
</ItemTemplate>
</asp:Repeater>
And our code to load. We ONLY load the main repeater data source, and THAT will trigger the item data bound event, and in that event then we deal with EACH separate instance of the child repeater.
Code like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * from MyHotels ORDER BY HotelName");
repHotels.DataSource = MyRstP(cmdSQL);
repHotels.DataBind();
}
protected void repHotels_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ( (e.Item.ItemType == ListItemType.Item) ||
(e.Item.ItemType == ListItemType.AlternatingItem))
{
// get child nested repeater
Repeater rChild = e.Item.FindControl("repPeopleBooked") as Repeater;
DataRowView rRow = ((DataRowView)e.Item.DataItem);
string strSQL = "SELECT * FROM People WHERE Hotel_ID = #id";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#id", SqlDbType.Int).Value = rRow["ID"];
rChild.DataSource = MyRstP(cmdSQL);
rChild.DataBind();
}
}
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
and we now get this:
So, we see the 3 main records that drive the main repeater, and then we see the child records for the nested repeater.
Now, in your case, you might only ever have one child record - but it don't matter. What really matters is that you have the ability to deal with, and bind, and have separate Eval() and data for that child repeater.

How can I retrieve the ex Exception object from session state and display the Message property of the exception?

ERROR.ASPX.CS page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace XEx21HandleErrors
{
public partial class Error : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblError.Text = ex.Message;
}
}
}
ERROR.ASPX
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Error.aspx.cs" Inherits="XEx21HandleErrors.Error" %>
<asp:Content ContentPlaceHolderID="mainPlaceholder" runat="server">
<h1 class="text-danger">An error has occurred</h1>
<div class="alert alert-danger">
<p><asp:Label ID="lblError" runat="server"></asp:Label></p>
</div>
<asp:Button ID="btnReturn" runat="server" Text="Return to Order Page"
PostBackUrl="~/Order.aspx" CssClass="btn btn-danger" />
</asp:Content>
CONFIRMATION.ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
namespace XEx21HandleErrors
{
public partial class Confirmation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var customer = (Customer)Session["Customer"];
var date = DateTime.Today.AddDays(1).ToShortDateString();
var text = $"Thank you for your order, {customer.FirstName}! It will be shipped on {date}.";
lblConfirm.Text = text;
SendConfirmation(customer, text);
}
private void SendConfirmation(Customer customer, string body)
{
try
{
MailMessage msg = new MailMessage("halloween#murach.com", customer.EmailAddress);
msg.Subject = "Order Confirmation";
msg.Body = body;
string html = "<html><head><title>Order Confirmation</title></head>"
+ "<body><h3>Thanks for your order!</h3>"
+ "<p>" + body + "</p></body></html>";
AlternateView view = AlternateView.CreateAlternateViewFromString(html, null, "text/html");
msg.AlternateViews.Add(view);
SmtpClient client = new SmtpClient("localhost");
client.Send(msg);
}
catch (Exception ex)
{
Session["Exception"] = ex;
Response.Redirect("~/Error.aspx");
}
}
}
}
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Order.aspx.cs" Inherits="XEx21HandleErrors.Order" %>
<asp:Content ID="mainContent" ContentPlaceHolderID="mainPlaceholder" runat="server">
<div class="row"><%-- row 1 --%>
<div class="col-sm-8"><%-- product drop down and info column --%>
<div class="form-group">
<label class="col-sm-6">Please select a product:</label>
<div class="col-sm-6">
<asp:DropDownList ID="ddlProducts" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="Name"
DataValueField="ProductID" CssClass="form-control">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString='<%$ ConnectionStrings:HalloweenConnection %>'
SelectCommand="SELECT [ProductID], [Name], [ShortDescription],
[LongDescription], [ImageFile], [UnitPrice] FROM [Products]
ORDER BY [Name]">
</asp:SqlDataSource>
</div>
</div>
<div class="form-group">
<div class="col-sm-12"><h4><asp:Label ID="lblName" runat="server"></asp:Label></h4></div></div>
<div class="form-group">
<div class="col-sm-12"><asp:Label ID="lblShortDescription" runat="server"></asp:Label></div></div>
<div class="form-group">
<div class="col-sm-12"><asp:Label ID="lblLongDescription" runat="server"></asp:Label></div></div>
<div class="form-group">
<div class="col-sm-12"><asp:Label ID="lblUnitPrice" runat="server"></asp:Label></div></div>
</div>
<div class="col-sm-4"><%-- product image column --%>
<asp:Image ID="imgProduct" runat="server" />
</div>
</div><%-- end of row 1 --%>
<div class="row"><%-- row 2 --%>
<div class="col-sm-12">
<div class="form-group">
<label class="col-sm-2">Quantity:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtQuantity" runat="server"
CssClass="form-control"></asp:TextBox></div>
<div class="col-sm-7">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="text-danger"
runat="server" ControlToValidate="txtQuantity" Display="Dynamic"
ErrorMessage="Quantity is a required field."></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" CssClass="text-danger"
ControlToValidate="txtQuantity" Display="Dynamic"
ErrorMessage="Quantity must range from 1 to 500."
MaximumValue="500" MinimumValue="1" Type="Integer"></asp:RangeValidator></div>
</div>
<div class="form-group">
<div class="col-sm-12">
<asp:Button ID="btnAdd" runat="server" Text="Add to Cart"
onclick="btnAdd_Click" CssClass="btn" />
<asp:Button ID="btnCart" runat="server" Text="Go to Cart"
PostBackUrl="~/Cart.aspx" CausesValidation="False" CssClass="btn" />
<asp:Button ID="btnCheckOut" runat="server" Text="Check Out"
PostBackUrl="~/CheckOut1.aspx" CausesValidation="False" CssClass="btn" />
</div>
</div>
</div>
</div><%-- end of row 2 --%>
</asp:Content>
Hello Everyone,
I am working on an application in which I want to display an exception error message when a user enters a email like this: email inside of the email textbox, but the problem that I am having is I am confused about how I can retrieve the ex Exception object from  session state and display the Message property of the exception in the label on the Error page. Here are some of my web application pages. I am trying to do this in the Error.aspx.cs (or code behind file). Do anyone think they can help?
Use try catch in those pages/events.
try {
//Do stuffs here such as pageload, click events and so on...
}
catch(Exception ex)
{
Session["ErrorMsg"] = ex.Message;
Response.Redirect("~/Error.aspx");
}
In Error.aspx
protected void Page_Load(object sender, EventArgs e)
{
lblError.Text = Session["ErrorMsg"] == null ? "" : Session["ErrorMsg"].ToString();
}

Take parameter from listview

i have this code:
protected void Button1_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(GetConnectionString());
{
System.Data.SqlClient.SqlCommand cmd;
sc.Open();
cmd = new System.Data.SqlClient.SqlCommand("SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;", sc);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#ID", System.Data.SqlDbType.Text)).Value = (TextBox)ListView1.FindControl("box1");
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
I need take value ID from listview, but with this code I have this error:
...expects the parameter '#ID', which was not supplied....
This part of my listview...
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID_zapas" DataSourceID="SqlDataSource1" style="text-align: center ">
<AlternatingItemTemplate>
<tr style="background-color: #e9ffe9;color: #284775;text-align:center">
<td>
<asp:TextBox ID="box1" runat="server" Text='<%# Eval("ID_zapas") %>' Visible="false" />
...
<td style="width:50px;background-color:white">
<asp:LinkButton ID="Button1" runat="server" OnClick="Button1_Click" Visible='<%# HttpContext.Current.User.IsInRole("admin") %>' CausesValidation="False" OnClientClick="javascript: return confirm('Opravdu chcete zápas zkopírovat?');">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Icons/copy.png" Width="29px" Height="29px" ToolTip="Zkopírovat zápas" />
</asp:LinkButton>
</td>
</tr>
</AlternatingItemTemplate>
Have you some idea?
As per comments, please try this:
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
var box1 = (TextBox)((LinkButton)sender).Parent.FindControl("box1");
using (var sc = new SqlConnection(GetConnectionString()))
{
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;";
cmd.Parameters.AddWithValue("#ID", box1.Text);
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
}
When using data-aware controls such as a ListView here, the controls are created with automatic unique IDs per data item. This means that you can have more than 1 of the same control (such as "box1" in this case) within the page that should be referenced by the data item (((LinkButton)sender).Parent which is ListViewDataItem, representing the row).
ListViewDataItem.FindControl will find controls of a specific server ID within its own child scope, allowing you to get values for controls within the same row of the button that is being clicked.

Cannot access checkbox checkedchanged event inside DataList

I have checkboxes inside a datalist itemtemplate..But i cant access checkbox chechedchange event. I set AutoPostBack as true. But still cant fire event.
Here my codes.
<ul class="commentlist" >
<asp:DataList ID="datalistYorum" runat="server" DataSourceID="ods_yorumlar"
RepeatLayout="Flow" ItemStyle-Wrap="True" RepeatDirection="Horizontal"
onitemcreated="datalistYorum_ItemCreated"
onitemdatabound="datalistYorum_ItemDataBound" onload="datalistYorum_Load"
ondatabinding="datalistYorum_DataBinding">
<ItemTemplate>
<li class="comment">
<div class="comment-body">
<div class="comment-author vcard">
<div class="lightbox-photo">
<a class="image-overlay" href='<%# "Foto/profil/foto_buyuk/" + Eval("Yorum_Profil_Foto_Buyuk") %>' data-rel="prettyPhoto" title='<%# Eval("Yorum_UserName")%>'>
<img src='<%# "Foto/profil/foto_kucuk/" + Eval("Yorum_Profil_Foto_Kucuk") %>' alt='<%# Eval("Yorum_UserName")%>' class="avatar" />
</a>
</div>
<cite class="fn"><asp:HyperLink ID="linkProfil" runat="server" Text='<%# Eval("Yorum_UserName")%>' NavigateUrl='<%# "~/profil.aspx?user_id="+ Eval("User_ID") %>'></asp:HyperLink></cite>
<cite class="fn-time"><%# Eval("Yorum_Gecen_Zaman")%></cite>
</div>
<p><%# Eval("Yorum_Text")%></p>
<div class="reply"><asp:CheckBox ID="checkLike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" />
<asp:ToggleButtonExtender ID="ToggleButtonLike" runat="server" TargetControlID ="checkLike" ImageHeight="32" ImageWidth="52" CheckedImageUrl="~/images/liked.png" UncheckedImageUrl="~/images/like.png" CheckedImageAlternateText="Like">
</asp:ToggleButtonExtender>
</div>
<div class="reply"><asp:CheckBox ID="checkDislike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" />
<asp:ToggleButtonExtender ID="ToggleButtonDislike" runat="server" TargetControlID="checkDislike" ImageHeight="32" ImageWidth="62" UncheckedImageUrl="~/images/dislike.png" CheckedImageUrl="~/images/disliked.png">
</asp:ToggleButtonExtender>
</div>
</div>
</li>
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="ods_yorumlar" runat="server"
DataObjectTypeName="Yorum" TypeName="yonet" SelectMethod="PostYorumlariGetir"
ondatabinding="ods_yorumlar_DataBinding"
onselecting="ods_yorumlar_Selecting" onselected="ods_yorumlar_Selected">
<SelectParameters>
and code behind:
protected void datalistYorum_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
CheckBox checkLike = (CheckBox)e.Item.FindControl("checkLike");
CheckBox checkDislike = (CheckBox)e.Item.FindControl("checkDislike");
if (!Page.IsPostBack)
{
checkLike.CheckedChanged += new EventHandler(checkLike_CheckedChanged);
checkDislike.CheckedChanged += new EventHandler(checkDislike_CheckedChanged);
}
}
}
public void checkLike_CheckedChanged(object sender, EventArgs e)
{
object user_id = Membership.GetUser().ProviderUserKey;
DateTime event_date = DateTime.Now;
CheckBox checkLike = (CheckBox)datalistYorum.FindControl("checkLike");
if (checkLike.Checked == true)
{
try
{
using (SqlConnection baglanti = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString.ToString()))
{
SqlCommand komut = new SqlCommand("sp_likeordislike", baglanti);
komut.CommandType = CommandType.StoredProcedure;
komut.Parameters.AddWithValue("#comment",1);
komut.Parameters.AddWithValue("#user_id", user_id);
komut.Parameters.AddWithValue("#likeordislike", 1);
komut.Parameters.AddWithValue("#event_date", event_date);
baglanti.Open();
komut.ExecuteNonQuery();
baglanti.Close();
}
}
catch (Exception)
{
throw;
}
}
}
But nothing happen.Thanks!
Unless you are adding the event handler for the 'checklike' Checkbox in Page_Load it looks as though the assignment is missing.
Change the 'checklike' Checkbox declaration as follows:
<asp:CheckBox ID="checkLike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" OnCheckedChanged="checkLike_CheckedChanged" />
Try this:
protected void checkDislike_CheckedChanged(Object sender, EventArgs e)
{
CheckBox cb = (CheckBox) sender;
DataListItem item = (DataListItem) cb.NamingContainer;
//
//
}
Your markup will look like this:
<asp:CheckBox ID="checkDislike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" OnCheckedChanged="checkDislike_CheckedChanged" />
Before trying this comment out all the other checkbox events
Check this link:

select index of listView is not working in ASP.NET

I am new to ASP.NET, I am making a search box in my application.
For example: if a user enters "abc" in the textbox, then the textbox will fetch data from the database which starts with "abc". I am passing this data to DataTable.
It works properly,
Here is my code snippet:
DataTable result = new DataTable();
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
Now I want to retrieve all this data in my <div> tag. so i tried using asp:ListView,
here is my code snippet,
it works properly, but now i want to navigate to new page when user select any row of listView, but i am unable to select any row..
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
</div>
</ItemTemplate>
Thanks In Advance !!
Any help will be appreciated.
EDIT:(SearchBox.aspx.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class SearchBox : System.Web.UI.Page
{
string connString;
DataTable result = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{ }
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("NextPage.aspx?id=" + lablId.Text, false);
}
}
(SearchBox.aspx)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchBox.aspx.cs" Inherits="SearchBox" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server" Height="30px" Width="179px"
OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Go"
Width="62px" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="false" runat="server" Text='<%#Eval("Scrip") %>'/>
</div>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:krunal_DBConnectionString2 %>"
SelectCommand="SELECT * FROM [SearchBoxData]"></asp:SqlDataSource>
</form>
</body>
</html>
You have to add a SELECT button in the ItemTemplate, see the complete working code.
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<%# Eval("Scrip")%>
<asp:LinkButton ID="SelectButton" runat="server" CommandName="Select" Text="Select" />
</ItemTemplate>
</asp:ListView>
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("CONTROL_ID");
}
Thanks
Deepu
Probably you will have to add the event for Selected index change:
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging">
In code behind you can get the selected row item like below.
Also you can place a label or hidden field so that you can get some data from those control and pass it in to the next page.. (might be id or something).
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="flase" runat="server" Text='<%#Eval("Id") %>' />
</div>
</ItemTemplate>
</asp:ListView>
void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("page.aspx?id="+lablId.Text,false);
}
}
Thanks
Deepu
Here you go,
Also remove the OnClick="callMethod" from the button. Since you have SelectedIndex method no need to have the onClick method.
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Button btn = (Button)item.FindControl("btn1");
if(btn != null)
{
var buttonText = btn.Text;
}
}
Hope this helps
Thanks
Deepu

Resources