I currently have a parent repeater and two child repeaters on my page. I am wanting to dynamically pull data from our database and display them within the repeaters. I followed the Microsoft guide and a few SO questions on how to do this, and this is what I have arrived at:
<!-- start parent repeater -->
<asp:repeater id="parentRepeater" runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %>"><%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater1 -->
<asp:repeater id="Repeater1" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater2 -->
<asp:repeater id="childRepeater2" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater2 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater1 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end parent repeater -->
And the code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
//Create the connection and DataAdapter for the Authors table.
string Connection = WebConfigurationManager.ConnectionStrings["md_dbConnectionString"].ConnectionString;
SqlConnection cnn = new SqlConnection(Connection);
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from EquipmentType", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "EquipmentType");
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from Make", cnn);
cmd2.Fill(ds, "Make");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select distinct MakeID, TypeID, YearID from Parts", cnn);
cmd3.Fill(ds, "Parts");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("myrelation",
ds.Tables["EquipmentType"].Columns["EquipmentTypeID"],
ds.Tables["Parts"].Columns["TypeID"]);
ds.Relations.Add("myrelation2",
ds.Tables["Make"].Columns["MakeID"],
ds.Tables["Parts"].Columns["MakeID"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds;
Page.DataBind();
//Close the connection.
cnn.Close();
}
If I load the page with only one child repeater, everything works fine, I get the correct data displaying, but when I add the second child repeater in, I get the following error message: Unable to cast object of type 'System.Data.DataRow' to type 'System.Data.DataRowView'. This fires on thedatasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>'` ASP line.
The tables that I am trying to pull from are structured this way:
EquipmentType
EquipmentTypeID | EquipmentTypeName
Make
MakeID | MakeName
Year
YearID
Parts
PartID | MakeID | YearID | TypeID
Each table references the Parts table.
More or less what I want the repeater to do is display all of the EquipmentTypes, then only display the make is we have a part for it in the database. Once the make is selected, then only display the year that we have parts for that make and equipmenttype in the database.
Did you try to cast it to DataRow:
<%# ((DataRow)Container.DataItem).GetChildRows("myrelation2") %>
For anyone else experiencing this issue. It could be that there is a missing tag at the top of the page. <%# Import Namespace="System.Data" %>
Related
Originally I was able to populate data in code-behind for the asp repeater like this:
public string guitarName = ConnectionClassGuitarItems.guitarName;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = GetData();
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
}
private void GetData()
{
string CS = ConfigurationManager.ConnectionStrings["musicStoreConnection"].ConnectionString;
string query = "SELECT * FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = #brand)";
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand comm = new SqlCommand(query, con))
{
con.Open();
comm.Connection = con;
comm.Parameters.Add(new SqlParameter("#brand", guitar));
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
comm.Parameters.Clear();
return ds;
}
}
}
Now, I wanted to change the code above into utilizing entity framework. So far i have already done this:
private void GetData()
{
MusicStoreDBEntities obj = new MusicStoreDBEntities();
List<stringInstrumentItem> name = new List<stringInstrumentItem>();
name = (from g in obj.stringInstrumentItems where g.brand.name == guitarName && g.type == "Guitar" select g).ToList();
DataSet ds = new DataSet();
}
I have already changed the raw sql into using linq to entity and added a new condition. But i don't know how to bind the data from entity framework to the asp repeater. I want to know how to bind data in asp repeater using entity framework.
Edited:
I've tried binding it as suggested below but it is giving me an exception error that it does not contain a property with the name 'name' pointing towards to this line of code: <%# Eval("name") %> <%# Eval("model") %>. As you can see, the name inside eval is really part of the table brand(please refer to the additional info below for insight of the two tables in my database). I don't have problems with this previously with the old approach of data binding using the dataset, but when i changed it to using entity framework, it does not recognize name anymore. Can it be just the query?
Here is the full code of the aspx file:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="repeater_ItemDataBound">
<ItemTemplate>
<div class="one-two">
<asp:LinkButton ID="linkButton" OnClick="Repeater1_OnClick" runat="server" CommandArgument='<%# Eval("brandId") + ";" + Eval("model") %>'>
<asp:Image ID="brandImage" runat="server" ImageUrl='<%# Eval("itemimage1") %>' height="130px" width="350px" />
</asp:LinkButton>
<div class="content">
<div id="label"><%# Eval("name") %> <%# Eval("model") %></div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Additional Info:
Table stringInstrumentItem(The column brandId is the foreign key and references the primary key of table brand, which is also named brandId):
itemId brandId model
1 1 xyz
2 1 abc
3 2 hjk
Table brand(which has the primary key called brandId that is referencing by the table strinInstrumentItem):
brandId name image
1 Ibanez xyz.jpg
2 Fender abc.jpg
3 Gibson hjk.jpg
private List<stringInstrumentItem> GetInstruments()
{
var musicStoreContext = new MusicStoreDBEntities();
List<stringInstrumentItem> instruments =
(from g in obj.stringInstrumentItems
where g.brand.name == guitarName && g.type == "Guitar"
select g
).ToList();
return instruments;
}
You can bind Repeaters and other controls directly to strongly typed objects, so just return a list of your model object.
Make sure to take advantage of strongly typed repeaters now.
I'm starting in ASP.NET. I need to write data from two tables that are linked via ID. I would like to write in the cycle.
Example: I have a table States and Cities table:
1.United states
a. New York
b. Washington
c. Los Angeles
d. Chicago
e. Houston
2. Russia
a. Moscow
b. St. Petersburg
c. Omsk
d. Kazan
3. France
a. Paris
b. Lyon
c. Marseille
In PHP I solve this problem as follows
`
// cycle cities
$sql = mssql_query("SELECT * FROM States");
while($row = mssql_fetch_assoc($sql))
{
$id_state = row['ID_State'];
echo ($ row ['Name_State']);
// cycle city with id state
$sql_city = mssql_query("SELECT * FROM City WHERE ID_State = '. $id_state.'");
while ($row_city = mssql_fetch_assoc($sql_city))
{
echo($row['Name_city']);
}
}
Alternatively, just advice on how the operation is called, I do not know how to properly ask this in search
I tried Repeater in repeater but i have problem withI tried repeater in repeater, but I have a problem with passing parameters given line
Repeater in Repeater
I tried also in DataReader DataReader, but this is an open DataReader reports an error.
C# MySQL second DataReader in DataReader while loop
I also tried a treeview, but I am in the city must have a name and the name of the State, the same "name" and "name" which I can not have this.
Treeview validation
I now tried good code
select.aspx.cs
SqlDataAdapter cmd1 = new SqlDataAdapter("SELECT * FROM V_Dic", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "Dic");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from T_Obdobi", cnn);
cmd2.Fill(ds, "Obdobi");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select * from V_AktualizaceDic", cnn);
cmd3.Fill(ds, "OsCislo");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("Obdobi",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["Obdobi"].Columns["ID_Dic"]);
//ds.Relations.add
ds.Relations.Add("OsCislo",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["OsCislo"].Columns["ID_Dic"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds.Tables["Dic"];
Page.DataBind();
select.aspx
<asp:Repeater ID="parentRepeater" runat="server">
<ItemTemplate>
<div class="accordion">
<div class="hlavni">
<%# DataBinder.Eval(Container.DataItem,"Dic") %>
</div>
<div class="rozbalovany">
<table>
<tr>
<td>Osobní číslo: </td>
<td><%# DataBinder.Eval(Container.DataItem,"OsCislo") %></td>
</tr>
<tr>
<td>Šetřené zdaňovací období: </td>
<td>
<div class="box2">
<!-- start child repeater -->
<asp:Repeater ID="childRepeater" DataSource='<%# ((System.Data.DataRowView)Container.DataItem).Row.GetChildRows("Obdobi") %>'
runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "[\"Obdobi\"]")%><br />
</ItemTemplate>
</asp:Repeater>
</div>
</td>
</tr>
</table>
<h3>Aktualizace:</h3>
<!-- end child repeater -->
<div class="box">
<table class="aktualizace" style="border: 1px solid #e9e9e9">
<tr>
<td><strong>Osobní číslo</strong></td>
<td>Jméno a Příjmení</td>
<td>Datum Aktualizace</td>
<td>Poznámka</td>
<td>Šetřené zdaňovací období</td>
<td>Změna Řešitele</td>
<td>Změna Plné moci</td>
<td>Záznam v Insolvenčním řejstříku</td>
<td>Významná změna s vazbou na data v OR</td>
<td>Jiná významná změna</td>
</tr>
<asp:Repeater ID="childRepeater2" DataSource='<%# ((System.Data.DataRowView)Container.DataItem).Row.GetChildRows("OsCislo") %>'
runat="server">
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "[\"OsCislo\"]")%></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
but, I can't add parameter to first select. I tried
cmd1.SelectCommand.Parameters.Add("#EvCislo", SqlDbType.NVarChar, 50, "EvCislo");
but program have error message "this constraint cannot be enabled as not all values have corresponding parent values."
this example i see here
You can use JOINS for fetch data from two tables using ID like
SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.id = table2.id WHERE table1.id = '1';
I have answer, add "false" behin relations
SqlDataAdapter cmd1 = new SqlDataAdapter("SELECT * FROM V_Dic", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "Dic");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from T_Obdobi", cnn);
cmd2.Fill(ds, "Obdobi");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select * from V_AktualizaceDic", cnn);
cmd3.Fill(ds, "OsCislo");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("Obdobi",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["Obdobi"].Columns["ID_Dic"], false);
//ds.Relations.add
ds.Relations.Add("OsCislo",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["OsCislo"].Columns["ID_Dic"], false);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds.Tables["Dic"];
Page.DataBind();
I have a nested repeater on my page like:
Aspx page:
<asp:Repeater ID="parentRepeater" runat="server">
<ItemTemplate>
<br />
<b><%# DataBinder.Eval(Container.DataItem,"question") %></b><br>
<!-- start child repeater -->
<asp:Repeater ID="childRepeater" DataSource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("relation") %>'
runat="server">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnCommand="LinkButton1_Command" CommandName="MyUpdate" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "[\"AnsId\"]")%>'><%# DataBinder.Eval(Container.DataItem, "[\"Ans\"]")%></asp:LinkButton>
<br>
</ItemTemplate>
</asp:Repeater>
<!-- end child repeater -->
</ItemTemplate>
</asp:Repeater>
Code behind:
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["star_report_con"].ConnectionString);
SqlDataAdapter cmd1 = new SqlDataAdapter("select questionId, question from questions", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "questions");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd2 = new SqlDataAdapter("SELECT AnsId, Ans, questionId FROM answers", cnn);
cmd2.Fill(ds, "answers");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("relation",
ds.Tables["questions"].Columns["questionId"],
ds.Tables["answers"].Columns["questionId"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds.Tables["questions"];
Page.DataBind();
//Close the connection.
cnn.Close();
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "MyUpdate")
{
//e.CommandArgument --> contain the Ansid value
//I want to also find which questions ans is clicked i.e the questionId
}
}
In my child repeater I have a linkbutton on click of which i need to do some computaion for which I need to know which questions answers wa being clicked. i.e in my LinkButton1_Command I want to fetch the AnsId along with QuestionId.
How will I get parent repeaters Id in button click event?
Try this ,
<%# ((RepeaterItem)Container.Parent.Parent).DataItem %>
If this does not work then try
<%# DataBinder.Eval(Container.Parent.Parent, "DataItem.YourProperty")%>
if you're in code-behind in the ItemDataBound method:
((Repeater)e.Item.NamingContainer.NamingContainer).DataItem
Very new to writing code, please be gentle...
I have a database that keeps track of images that I post online, who was in the image, date taken, etc. I then have an ASPX page that based on the ID I pass in brings me back a gridview of the image, location online etc. This helps me keep track of how many places I may have used a single image.
Everything works great, but I get one row per image URL in my grid view. I want to have the image appear once on my page, then one of the cells list out the URLs.
Here is my C#:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["db2257conn"].ConnectionString;
String strQuery = "select mFirstName, mDOB, cURL, fID, fURL, cDate from vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN(mID1, mID2, mID3) and cactive = 1 order by cDate, fType, fName, cURL";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
}
Here is the ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="modelcontent2.aspx.cs" Inherits="modeldatabase.modelcontent2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" Font-Names="Arial" OnSelectedIndexChanged="GridView2_SelectedIndexChanged" >
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="fURL" DataTextField="furl" DataTextFormatString="<img src='{0}' width='200' border='0' />" Target="_blank" HeaderText="Image Link" Text="Image Link" />
<asp:BoundField DataField ="cDate" HeaderText ="Shoot Date" />
<asp:BoundField DataField ="mFirstName" HeaderText="Model First Name" />
<asp:BoundField DataField="mDOB" HeaderText="DOB" />
<asp:BoundField DataField="fID" HeaderText="File ID" />
<asp:HyperLinkField DataNavigateUrlFields="cURL" DataTextField="cURL" HeaderText ="URL" Target="_blank" Text="URL" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
And my rep is too new to post an image of the results, but suffice it to say I see multiple rows for the same image, one for each URL.
I'd like to see the image and other data as a single row, then in the URL column have all of the URLs that the image appears at.
Maybe not very performant but try a subselect
String strQuery = "select mFirstName, mDOB, (SELECT cURL + ',' FROM vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN (mID1, mID2, mID3)) , fID, fURL, cDate from vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN(mID1, mID2, mID3) and cactive = 1 order by cDate, fType, fName, cURL LIMIT 1";
I'm not sure if it works, didn't use sql for a long time
Question: Why do you have three columns for IDs? (mID1, mID2, mID3)
What you are defining is called a "1 to many" relationship.
Gridview's are designed to show multiple rows tabular type data. If you want to display 1 image and multiple rows of associated data there are several ways of doing this.
Typically this would require 2 database calls:
one that returns the image source link
one that returns the rows of associated data.
Since the first call is really only providing an img src you don't really need a databound control for that, just obtain the string and drop it into an <asp:Image /> control or an <asp:ImageButton /> (if you prefer the image to be a link) and set the ImageUrl property
The second call is returning multiple rows of data, use your existing Gridview, you only need to remove the image reference.
I am making a project in ASP.NET WebForms. Although I have done it so many times but dropdown list is troubling me a lot this time.
I fetch items from DB and then add them to my dropdown list one by one using FOR loop. That works fine. But the problem is that I cannot select an item from list comfortably, whenever I try to select an item from the drop down list, it snaps the selection to the first element, it becomes very difficult to select the desired item.
How could I fix that?
Suppose I move my cursor over the 9th item in the list then also it selects the 1st and 9th item alternatively so fast that I see both of them as selected.
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.Items.Clear();
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
con.Open();
adp = new SqlDataAdapter("select distinct family_head from family", con);
DataSet ds = new DataSet();
adp.Fill(ds, "family");
con.Close();
for (int i = 0; i < ds.Tables["family"].Rows.Count; i++)
DropDownList1.Items.Add(ds.Tables["family"].Rows[i][0].ToString());
}
}
ASPX
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DropDownList ID="DropDownList1" runat="server" Width="150px">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" Width="150px">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Height="30px" onclick="Button1_Click"
Text="Submit" Width="145px" BackColor="#465767" ForeColor="White" />
<asp:RoundedCornersExtender ID="Button1_RoundedCornersExtender" runat="server"
Enabled="True" TargetControlID="Button1" Corners="All" Radius="10">
</asp:RoundedCornersExtender>
<br />
<br />
<br />
</asp:Content>
A CSS Keyframes Animation is working in page background, Can that be a cause?
There seems to be some kind of confusion, as to how databinding works for WebControls. The best reference for that is: http://msdn.microsoft.com/en-us/library/ms178472.aspx
Under the assumption, that all the binding code for DropDownList1 is shown:
DropDownList1.Items.Clear();
shouldn't be neccesary, as the items shouldn't persist per PostBack. (At least I assume that, because all Items will be lost after each PostBack if the DataSource isn't bound again).
The DropDownList needs have the items on each PostBack, if you want to use the DropDownList. You are using
if (!Page.IsPostBack)
which means, that you don't bind the items again, if you have a PostBack. In the link posted above, you can see that Controls set their properties (like which item was selected before clicking a Button) during the LoadEvent, which means that the items need to be binded earlier in the lifecycle, like during OnInit.
Try something like this:
protected void BindDropDownList1()
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
con.Open();
adp = new SqlDataAdapter("select distinct family_head from family", con);
DataSet ds = new DataSet();
adp.Fill(ds, "family");
con.Close();
for (int i = 0; i < ds.Tables["family"].Rows.Count; i++)
DropDownList1.Items.Add(ds.Tables["family"].Rows[i][0].ToString());
}
protected override void OnInit(EventArgs e)
{
this.BindDropDownList1();
base.OnInit(e);
}
Another suggestion would be to you the DataSource property of the DropDownList, instead of DropDownList1.Items.Add. If you use this approach, you need to set the DataKeyValue and DataKeyMember properties of the DropDownList:
protected void BindDropDownList1()
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
con.Open();
adp = new SqlDataAdapter("select distinct family_head from family", con);
DataSet ds = new DataSet();
adp.Fill(ds, "family");
con.Close();
DropDownList1.DataSource = ds;
DropDownList1.DataBind();
}
Edit:
I think I found your error. You are using controls from the AjaxControlToolKit, but are still using the ScriptManager. For about 2 years, controls from the AjaxControlToolKit require the ToolkitScriptManager. Replace the ScriptManager with a ToolkitScriptManager.