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
Related
I am little confused for creating website menu & sub menus which is completely dynamic & made from database. For Menus I used Listview Control which is fine now all menus have submenus(child menu) as well which is based on menus. Now I don't understand how to do it. I guess using nested ListView would be good for this but I need an hint how to bind nested listview?
This is my main Listview
<asp:ListView ID="mainMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Private Sub bigMenu()
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM mainMenu WHERE status = 'active' order by CAST(position as SIGNED INTEGER) asc"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
mainMenu.DataSource = dt
mainMenu.DataBind()
End Using
End Using
End Using
End Sub
You need to use ListView ItemDataBound to bind your nested listview. ItemDatBound will get rows value for you. See the below code I done for you
<asp:ListView ID="mainMenu" runat="server" DataKeyNames="enter column name you want">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Protected Sub onItemDataBound(sender As Object, e As ListViewItemEventArgs)
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim itm As ListViewDataItem = CType(e.Item, ListViewDataItem)
Dim name As String = mainMenu.DataKeys(itm.DataItemIndex)("enter your datakeyname")
Dim childMenu As ListView = TryCast(e.Item.FindControl("childMenu"), ListView)
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM tablename WHERE column = '" + name + "'"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childMenu.DataSource = dt
childMenu.DataBind()
End Using
End Using
End Using
End If
End Sub
I'm using this article as a guide to doing a nested data bind of my two tables 'Comment' 'CommentOtherAuthor': http://support.microsoft.com/kb/306154. There may be many authors to one comment. The code I have is here:
.ASPX:
<asp:Repeater ID="rptComments" runat="server">
<ItemTemplate>
<div class="comment-data">
<h3 class="item">Submitted to <%# GetPageDetails(Eval("nodeid")) %> article on <%# Eval("created") %></strong></h3>
<p class="item"><strong>Name</strong> <%# Eval("firstname") %> <%# Eval("surname") %></p>
<p class="item"><strong>Occupation</strong> <%# Eval("occupation") %></p>
<p class="item"><strong>Affiliation</strong> <%# Eval("affiliation") %></p>
<p class="item"><strong>Email</strong> <a href='mailto:<%# Eval("email") %>'><%# Eval("email") %></a> <em>Publish email: <%# Eval("publishemail") %></em></p>
<p class="item"><strong>Competing interests?</strong> <%# Eval("competingintereststext") %> </p>
<p class="item"><strong>eLetter title</strong> <%# Eval("title") %></p>
<p><%# Eval("comment").ToString().Replace("\n", "<br/>")%></p>
<div class="additional-authors">
<h3>Additional authors</h3>
<asp:Repeater id="rptAdditionalAuthors" runat="server" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' >
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "[\"firstname\"]")%><br>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Codebehind:
private void BindData()
{
SqlConnection cnn = new SqlConnection(GlobalSettings.DbDSN);
SqlDataAdapter cmd1 = new SqlDataAdapter(string.Format("select * from Comment {0} order by created desc", Filter), cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "comments");
//Create a second DataAdapter for the additional authors table.
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from CommentOtherAuthor", cnn);
cmd2.Fill(ds, "additionalAuthors");
//Create the relation between the comments and additional authors tables.
ds.Relations.Add(
"myrelation",
ds.Tables["Comment"].Columns["id"],
ds.Tables["CommentOtherAuthor"].Columns["commentid"]
);
//Bind the Authors table to the parent Repeater control, and call DataBind.
rptComments.DataSource = ds.Tables["additionalAuthors"];
rptComments.DataBind();
}
However, when running this it throws a System.NullReferenceException on the line ds.Relations.Add(
I'm really not sure where to start in fixing this as I'm way out of my depth here.
Can anyone advise how to get this working?
Thanks.
Got it! There was no actual foreign key constraint joining the tables. With that in place this now works.
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
I want to bind my Listview but I can't. I dont know what I am doing wrong here. When I press ctrl+f5, the page is empty.
My Code is:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}
try this:
first your item template is worng, and also you need to fill the data adabter form the Data Table
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%# Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%# Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}
The last 3 lines of code in your code-behind tell the whole story:
DataTable dt = new DataTable();
ListView1.DataSource = dt;
ListView1.DataBind();
You're instantiating a new, empty DataTable and binding ListView1 to it. Thus, behaving correctly and exactly as designed, your ListView is displaying zero records from the empty DataTable.
You'll want to fetch the data from the DataAdapter before you bind anything to it. Something like this:
var students = new DataSet();
da.Fill(students, "Student");
if (students.Tables.Count == 1)
{
ListView1.DataSource = students.Tables[0];
ListView1.DataBind();
}
Note: There may be a more direct way to fetch the DataTable. I haven't worked with DataSets and DataTables in a long time, but .Fill() may be able to directly use a DataTable and skip my checking of a valid table in the DataSet above.)
Your datatable is never getting populated. Have a look at the following:
http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx
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.