Asp.Net binding specific fields of sql query to Listview - asp.net

I have a listview that has a few different controls. I need to bind specific fields of a query to certain parts of a control. The table contains a friendid and a firstname. I want to put the friendid at the end of a URL. I want to put the firstname in the text of a label. There will be multiple friends returned on the query. The listview should show all in a separate row. Here is what I have, which is obviously not right.
<asp:ListView ID="lvFriends" runat="server">
<LayoutTemplate>
<ul ID="itemPlaceholderContainer" runat="server" style="">
<li ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<div style="float:left;">
<a id="A1" href='<%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsProfile.aspx?friend={0}", Container.DataItem)) %>' runat="server"><asp:Image ID="ImageButton1" ImageUrl='<%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsThumbImage.aspx?friend={0}", Container.DataItem)) %>' runat="server" /></a>
</div>
<div style="margin-left:300px;">
<ul>
<li><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FriendFN") %>' /></li>
</ul>
</div>
</li>
<div style="clear:both;"></div>
</ItemTemplate>
<ItemSeparatorTemplate><br /></ItemSeparatorTemplate>
</asp:ListView>
CODE BEHIND:
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * from [Friends] WHERE [UserId] = #UserId";
cmd.Parameters.AddWithValue("#UserId", User.Identity.Name);
DataTable dtFriends = new DataTable();
dtFriends.Columns.Add("FriendId");
dtFriends.Columns.Add("FriendFN");
SqlDataReader nwReader = cmd.ExecuteReader();
while (nwReader.Read())
{
string RdFriendId = nwReader["FriendId"].ToString().ToLower();
string RdFriendFN = nwReader["FriendFirstName"].ToString().ToLower();
dtFriends.Rows.Add(new object[] {RdFriendId, RdFriendFN});
}
nwReader.Close();
Session.Add("FriendsTable", dtFriends);
conn.Close();
lvFriends.DataSource = dtFriends;
lvFriends.DataBind();
}
}

I would look into using a repeater control instead.

Related

How to return parent field value to inner repeater?

I have below nested repeater, I need to return ID value from parent repeater then put it inside the Nested repeater.
ID_Parent=<% '?????? %> :
<asp:Repeater runat="server" ID="rp_outer">
<ItemTemplate>
<div id="<%#Eval("ID") %>">
<h4><%#Eval("Ename") %></h4>
<ul class="menu-items">
<asp:Repeater runat="server" ID="rp_inner_floorg" Visible="true"
DataSource='<%#(Container.DataItem).Row.GetChildRows("rltbls") %>'>
<ItemTemplate>
<li>
<a href='Products.aspx?ID_Parent=<% '?????? %>&InnerID=<%#CType(Container.DataItem, DataRow)("ID")%>'>
</a>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
**code-behind**
'Parrent
varSql = "SELECT ID,CatEname,HeadImg from qrywebsite_OuterMenue"
DataAdapter_1 = New SqlDataAdapter(varSql, varDbconn)
DataAdapter_1.Fill(ds, "tblCategory")
'Child
varSql = "select ID,Cat_Fkey,[SubCatEname] from qrywebsite_InnerSubCatMenu order by [Sequence]"
DataAdapter_2 = New SqlDataAdapter(varSql, varDbconn)
DataAdapter_2.Fill(ds, "tblSubCate")
ds.Relations.Add("rltbls", ds.Tables(0).Columns("ID"), ds.Tables(1).Columns("Cat_Fkey"), False)
ds.Relations("rltbls").Nested = true
rp_outer_catwgroy.DataSource = ds.Tables(0)
rp_outer_catwgroy.DataBind()
ds.Dispose()
DataAdapter_1.Dispose()
Replace ID_Parent=<% '?????? %> with:
<%# DataBinder.Eval(((RepeaterItem)Container.Parent.Parent).DataItem, "ID")%>

Get checked checkbox list values inside a repeater

How can I get checked values form checkboxlists inside a repeater, I have no idea how collect all checked values in a collection list.
<asp:Repeater runat="server" ID="rp_outer" OnItemDataBound="rp_outer_ItemDataBound">
<ItemTemplate>
<a class="collapsed btn" data-toggle="collapse" data-target="#Col<%#Eval("ProID") %>"> <%#Eval("PropEName") %></a>
<div id="Col<%#Eval("ProID") %>" class="collapse in">
<asp:CheckBoxList ID="cbxlist" runat="server" CssClass="filter-ul" DataSource='<%# DataBinder.Eval(Container.DataItem, "rltbls") %>' DataValueField='ID' DataTextField='ValuesEName'>
</asp:CheckBoxList>
</div>
<hr />
</ItemTemplate>
</asp:Repeater>
you need grouping items with ProId.
<ItemTemplate>
<a class="collapsed btn" data-toggle="collapse" data-target="#Col<%#Eval("ProID") %>"> <%#Eval("PropEName") %></a>
<asp:HiddenField runat="server" ID="ProID" Value="<%#Eval("ProID") %>"/>
<div id="Col<%#Eval("ProID") %>" class="collapse in">
....
You can create a dictionary list that uses ProId as a key
private Dictionary<string, List<string>> GetCheckedItems()
{
Dictionary<string, List<string>> checkedItemsList = new Dictionary<string, List<string>>();
foreach (RepeaterItem item in rp_outer.Items)
if (item.ItemType == ListItemType.Item)
{
CheckBoxList itemCheckBoxList = item.FindControl("cbxlist") as CheckBoxList;
if (itemCheckBoxList != null)
{
string proIdValue = (item.FindControl("ProID") as HiddenField).Value;
List<string> checkedItems = new List<string>();
foreach (ListItem checkBoxItem in itemCheckBoxList.Items)
if (checkBoxItem.Selected)
checkedItems.Add(checkBoxItem.Value);
checkedItemsList.Add(proIdValue, checkedItems);
}
}
return checkedItemsList;
}

losing the first result of retrieved data when binding it to repeater control

I am developing a social network in which i must show a list of friends to the current user.
i am using SqlDataReader to retrieve data from database then bind it by a repeater , the problem is that the repeater always skip the first result so it only shows the n-1 results out of n. anybody can explain to me this behaviour?
my code is:
string cmdstr2 = "SELECT students.fname, students.lname,students.username FROM students INNER JOIN friends ON students.username = friends.tostudent WHERE (friends.fromstudent ='" + cuser + "')";
SqlCommand cmd2 = new SqlCommand(cmdstr2, sc);
SqlDataReader rd = cmd2.ExecuteReader();
if (rd.Read())
{
Repeater1.DataSource = rd;
Repeater1.DataBind();
}
in the design view, i have written this code to include the repeater in the page:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<div style="font-size:xx-large;">
الأصدقاء</div>
</HeaderTemplate>
<ItemTemplate>
<div style="font-size:x-large; color:Black; margin-right:0px; margin-top:0px;">
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "student.aspx?user="+DataBinder.Eval(Container.DataItem,"username")%>' >
<%#DataBinder.Eval(Container.DataItem, "fname")%> <%#DataBinder.Eval(Container.DataItem, "lname")%>
</asp:HyperLink>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Your rd.Read() in your if statement is advancing it 1 record
Try using:
if (rd.HasRows)

ASP display subcategories with similar categories using repeater

I'm trying to build a large menu with div's for each "Category". In each div the H3 is based on the "Category" that I'm pulling from a SQL table. Under the will be a with list items that are subCategories for each Category...which are links.
In the table there a bunch of Category items.
How can I loop through to show the Category and the subCategories associated with that category?
Here is how my html is set up:
<asp:Repeater id="dlCategories" runat="server" DataSourceID="LarryColeSub">
<ItemTemplate>
<div class="col_1">
<h3><%# Eval("Category") %></h3>
<ul>
<ItemTemplate>
<li><a id="cmdSubCategory" class="sectioncontentslink" href='default.aspx?rPage=ToolList&subCatID=<%# Eval("SubCategoryID")%>'>
<%# Eval("SubCategory") %></a></li>
</ItemTemplate>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
Here is my sqlDataSource:
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:LarryCole %>" ID="LarryColeSub" runat="server" SelectCommand="SELECT [SubCategoryID],[SubCategory],[Category],[fkCategoryId] FROM [tblSubCategory]">
When I run this now it (obviously) creates a div for each subCategory vs a div for each Category.
<%# Control Language="c#" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Configuration" %>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e) {
if (!Page.IsPostBack) {
SqlConnection MyConnection;
SqlCommand MyCommand;
SqlDataAdapter MyAdapter;
DataTable MyTable;
DataSet ds;
ds = new DataSet();
MyConnection = new SqlConnection();
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["db_name_here"].ConnectionString;
MyCommand = new SqlCommand();
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = MyConnection;
MyCommand.CommandText = "SELECT * FROM tblSubCategory";
MyTable = new DataTable();
MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand = MyCommand;
MyAdapter.Fill(ds,"SubCategory");
MyCommand.Dispose();
MyCommand.CommandText = "SELECT * FROM tblCategory";
MyTable = new DataTable();
MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand = MyCommand;
MyAdapter.Fill(ds,"Category");
MyCommand.Dispose();
ds.Relations.Add("myrelation",ds.Tables["Category"].Columns["CategoryID"], ds.Tables["SubCategory"].Columns["fkCategoryID"]);
//populate parent repeater
rpCategories.DataSource = ds.Tables["Category"];
rpCategories.DataBind();
MyAdapter.Dispose();
MyConnection.Dispose();
}
}
</script>
//html repeater code
<asp:Repeater id="rpCategories" runat="server">
<ItemTemplate>
<div class="col_1">
<h3><%# DataBinder.Eval(Container.DataItem,"Category") %></h3>
<ul>
<asp:Repeater id="rpSubCategories" runat="server" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>'>
<ItemTemplate>
<li><a id="cmdSubCategory" class="sectioncontentslink" href='default.aspx?varName=BlahBlah&subCatID=<%# ((DataRow)Container.DataItem)["SubCategoryID"] %>'>
<%# ((DataRow)Container.DataItem)["SubCategory"] %></a>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</ItemTemplate>
</asp:Repeater

ListView Rendering image issue. [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Rendering bytes from sql server to an image control?
<asp:ListView ID="lvGallery" runat="server" DataSourceID="SqlDataSource1">
<LayoutTemplate>
<table runat="server" id="tableGallery">
<tr runat="server" id="itemPlaceHolder">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr><td>
<div class="box_img2">
<div class="g_size">
<a runat="server" id="linkImage"><img id="Image1" runat="server" src="MyImage.jpg" /></a>
</div>
</div>
</td></tr>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=CHANDAN-PC;Initial Catalog=Metamorphism;User ID=sa;password=chandan;"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [Image] FROM [GalleryImages]"></asp:SqlDataSource>
public void ProcessRequest(HttpContext context)
{
//write your handler implementation here.
string username = Convert.ToString(context.Request.QueryString["username"]);
if (username != null)
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
byte[] arrContent;
DataRow dr;
string strSql;
strSql = "Select Image from GalleryImages where username = '" + username + "'";
da = new SqlDataAdapter(strSql, connection.ConnectionString);
da.Fill(ds);
dr = ds.Tables[0].Rows[0];
arrContent = (byte[])dr["ImageFile"];
context.Response.ContentType = "jpeg";
context.Response.OutputStream.Write(arrContent, 0, arrContent.Length);
context.Response.End();
}
}
I have added httphandlers tag in web.config.
I think you need to change this
<div class="box_img2">
<div class="g_size">
<a runat="server" id="linkImage">
<img id="Image1" runat="server" src='<%# Eval( HttpContext.Current.Request.QueryString["username"] ,"YourGenericHandler.ashx?username={0}") %>' /></a>
</div>
</div>

Resources