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();
Related
I am trying to fetch table category and based on that table category the multiple details of that category will have to automatically fetch under this following category but unfortunately multiple table is created under this single category.
First of all I have created tbl_category(ID{PK}, catName) table on DB. Then created tbl_categoryDetails(ID{PK}, catId{FK}, catDetails). So I have needed multiple categoryDetails fields under single category.
So then I have to fetch this catName with their details part by part. I have attached of the static table, I need this way table data will be fetched Static Table Image.
But Unfortunately I am getting data this way My Dynamic Table Image. The categoryName fetch multiple time but I want single time. I am using repeater control to fetch data from DB. please help me to solve this problem.
My Forms.aspx code is here:
<asp:Repeater ID="rptr_form" runat="server">
<ItemTemplate>
<section class="about">
<div class="container">
<div class="row no-gutters d-flex justify-content-center">
<div class="flex-column justify-content-center about-content minwidth">
<div class="section-title">
<div class="mycontent-center">
<h2 style="margin-bottom: -5px;" data-toggle="collapse" role="button" href="#collapseExample19" aria-expanded="false" aria-controls="collapseExample19"><%#Eval("form_categoryname") %>   <i class="fa fa-chevron-circle-down" aria-hidden="true"></i></h2>
<br />
<div class="content-style collapse tbl-scroll" id="collapseExample19">
<table class="table table-striped">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">No</th>
<th scope="col">Bangla</th>
<th scope="col">English</th>
</tr>
</thead>
<tbody>
<tr class="table-info">
<td><%#Eval("form_details") %></td>
<td><%#Eval("form_no") %></td>
<td><a href="<%# "../" + Eval("form_bengali_path") %>" target="_blank">
<img src="assets/image/pdf.jpg" style="height: 30px; width: 48px;" /></a></td>
<td class="center"><a href="<%# "../" + Eval("form_english_path") %>" target="_blank">
<img src="assets/image/pdf.jpg" style="height: 30px; width: 48px;" /></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</ItemTemplate>
</asp:Repeater>
My Forms.aspx.cs code is here:
protected void AllFormLoad()
{
try
{
using (SqlConnection con = new SqlConnection(strcon))
{
SqlCommand cmd = new SqlCommand("spFormDetailsFetch", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
rptr_form.DataSource = dt;
rptr_form.DataBind();
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
Sql Query
select D.ID, C.form_categoryname, D.form_details, D.form_no, D.form_bengali_path, D.form_english_path from tbl_form_details D inner join tbl_form_category C on D.form_categoryId = C.ID order by form_categoryname
Sounds like you really need two nested loops here, one for categories and one for each category's details. You should add the SQL statement that is pulling the data to your question so we can tell for sure, but I'm guessing the duplication is because of the join.
This isn't a wonderful solution, but what I've done before in this scenario is to use the ItemDataBound event in codebehind to show the header only for the first row of each category. So you keep track of the category id somewhere, maybe in a hidden field, and as itemdatabound loops through the records, when the category id changes, you show the header for that item record, and then update the category id. Then as long as the category id stays the same, you keep hiding the header. When it changes again, you know you've hit the records for the next category and it's time to show the header again.
Below is a simplified example, note that you need to wrap a placeholder around the header and foot sections so you can hide them as needed. In your case that would be everything above and below the tr.
Repeater code:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:PlaceHolder ID="pnlHead" runat="server">
<section>
<h2><%#DataBinder.Eval(Container.DataItem, "form_categoryname").ToString()%></h2>
</asp:PlaceHolder>
<div>
<%#DataBinder.Eval(Container.DataItem, "form_details").ToString()%>
<asp:HiddenField ID="HiddenFieldID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem,"form_categoryname") %>' />
</div>
<asp:PlaceHolder ID="pnlFoot" runat="server">
</section>
</asp:PlaceHolder>
</ItemTemplate>
</asp:Repeater>
Page Load:
public string CurrentCategory = "";
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader rs = DB.GetRS("select D.ID, C.form_categoryname, D.form_details, D.form_no, D.form_bengali_path, D.form_english_path from tbl_form_details D inner join tbl_form_category C on D.form_categoryId = C.ID order by form_categoryname", con))
{
Repeater1.DataSource = rs;
Repeater1.DataBind();
}
}
int idx = 0;
// where head is visible, show the foot for the previous row
foreach (RepeaterItem item in Repeater1.Items)
{
if (idx > 0)
{
bool headvisible = item.FindControl("pnlHead").Visible;
if (headvisible)
{
Repeater1.Items[idx - 1].FindControl("pnlFoot").Visible = true;
}
}
idx++;
}
}
OnItemDataBound:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
HiddenField HiddenFieldID = e.Item.FindControl("HiddenFieldID") as HiddenField;
string itemCategory = HiddenFieldID.Value;
if (itemCategory == CurrentCategory)
{
PlaceHolder pnlHead = e.Item.FindControl("pnlHead") as PlaceHolder;
PlaceHolder pnlFoot = e.Item.FindControl("pnlFoot") as PlaceHolder;
pnlHead.Visible = false;
pnlFoot.Visible = false;
}
else
{
//Now we're in a new category, so show header
PlaceHolder pnlHead = e.Item.FindControl("pnlHead") as PlaceHolder;
PlaceHolder pnlFoot = e.Item.FindControl("pnlFoot") as PlaceHolder;
pnlHead.Visible = true;
pnlFoot.Visible = false;
CurrentCategory = itemCategory;
}
}
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 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" %>
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
I have a repeater I want to add a title to in the HeaderTemplate from my database
This is my code so far
<asp:Repeater ID="topicView" runat="server">
<HeaderTemplate>
<tr>
<td>
<h1><%#DataBinder.Eval(Container.DataItem, "TopicName")%></h1>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem, "PostBody")%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td>
</td>
</tr>
</FooterTemplate>
</asp:Repeater>
But nothing is displaying in my header. I heard that you can't use databinder in the header, so could anyone recommend how to do this?
this is my CS code
string topic = Request.QueryString["topicid"].ToString();
// Define the select statement.
// All information is needed
string selectSQL = "SELECT * FROM PostView WHERE TopicID ='" + topic + "'";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
con.Open();
SqlDataReader postView = cmd.ExecuteReader();
topicView.DataSource = postView;
topicView.DataBind();
You don't need to bind to the data source, just bind to a simple property of the page. Use this in the HeaderTemplate:
<h1><%# TopicName %></h1>
Then add TopicName as a public property to the code-behind.
public string TopicName { get; set; }
Then set it when you run the query:
TopicName = Request.QueryString["topicid"].ToString();
Side Note
Not sure if you're aware, but you should be careful of SQL injection. Instead of injecting the query string directly into your SQL query, it's a good idea to use
string selectSQL = "SELECT * FROM PostView WHERE TopicID ='{0}';
Then add the topic to your SqlCommand as a parameter.