How to bind data in asp repeater using entity framework? - c#

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.

Related

change Panel Visibilty on SqlDataReader value and trim first two characters from Eval string C#

Currently i have two problems.
Problem 1. Im trying to change the Visibility of two Panels based on what value the reader gets from reader["Maskine_Type"].ToString() as you can see in the Codebehind below. Because the Panels are inside a repeater i also use the:
Panel PanelTilbud = (Panel)Page.FindControl("PanelTilbud"); again you can see below. however, when i run the code it gives me a Object reference not set to an instance of an object on PanelTilbud.Visible = true; i assume because it still cant find the Panels. i tested with panels outside of the repeater and it works fine.
I also tried to make the Repeater OnItemDataBound="Repeater1_ItemDataBound"
and changed to Panel PanelTilbud = (Panel)e.Item.FindControl("PanelTilbud");
However then i get the error Insufficient stack to continue executing the program safely
Problem 2.
Inside one of the panels, i run this code
<%# (Eval("Maskine_Tilbud").ToString().Substring(Eval("Maskine_Tilbud").ToString().Length - 2))%>
in order to remove the first two characters in the string from Eval("Maskine_Tilbud") which works fine, however most records in the database will have a null inMaskine_Tilbud and if its null i get the error StartIndex cannot be less than zero which makes sense, but i dont know how else to remove the first two characters from Eval("Maskine_Tilbud")
.aspx markup
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Panel ID="PanelTilbud" runat="server" Visible="false">
<hr />
<h4 class="radfont text-center">Tilbud! -<%# (Eval("Maskine_Tilbud").ToString().Substring(Eval("Maskine_Tilbud").ToString().Length - 2))%>% pr dag!</h4>
</asp:Panel>
<asp:Panel ID="PanelNormal" runat="server">
<hr />
<h4 class="text-center orangeFont"><%#Eval("Maskine_pris") %><span class="hvidfont">,- pr dag inkl moms</span>
<span class="orangeFont">(<%#Eval("Maskine_Upris") %>,- ekskl)</span>
</h4>
<hr />
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
My Codebehind - in Page_Load
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT top 1 * FROM [Maskiner] INNER JOIN Maskine_kategori ON Maskiner.Maskine_Kategorinavn = Maskine_kategori.Maskine_kategori_id WHERE ([Maskine_id] = #Maskine_id)";
cmd.Parameters.Add("#Maskine_id", SqlDbType.Int).Value = Request.QueryString["Maskine_id"];
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
Panel PanelTilbud = (Panel)Page.FindControl("PanelTilbud");
Panel PanelNormal = (Panel)Page.FindControl("PanelNormal");
if (reader.Read())
{
if (reader["Maskine_Type"].ToString() == "Tilbud")
{
PanelTilbud.Visible = true;
PanelNormal.Visible = false;
}
if (reader["Maskine_Type"].ToString() == "Normal")
{
PanelTilbud.Visible = false;
PanelNormal.Visible = true;
}
}
conn.Close();
DataTable select_favorit_db = new DataTable();
SqlDataAdapter dt = new SqlDataAdapter(cmd);
dt.Fill(select_favorit_db);
Repeater1.DataSource = select_favorit_db;
Repeater1.DataBind();
I hope you can understand my questions.
Late to the party here. Just thought I should add that you can have methods in your page and use them in your data binding expressions. Sample:
ASPX:
<form id="form1" runat="server">
<asp:Repeater ID="rep" runat="server">
<ItemTemplate>
<asp:Label ID="lab" runat="server"
Text='<%# Trim2Chars(Eval("test")) %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
//create fake data for demo and bind to repeater
var data = Enumerable.Range(0, 10).Select(i => new { test = "foo " + i });
rep.DataSource = data;
rep.DataBind();
}
public string Trim2Chars(object input)
{
string inputString = input as string;
if (inputString == null)
return "";
if (inputString.Length < 2)
return inputString;
return inputString.Substring(2);
}
This way, you can keep the ASPX file a bit cleaner and have more complex data binding expressions evaluated in the code behind.
You can set the Visibility in the Control itself
<asp:Panel ID="PanelTilbud" runat="server" Visible='<%# Eval("Maskine_Type").ToString() == "myValue" %>'>
</asp:Panel>
Or in the ItemDataBound event code behind
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//use findcontrol to find the panel and cast it as one
Panel panel = e.Item.FindControl("PanelTilbud") as Panel;
//get the current datarowview
DataRowView row = e.Item.DataItem as DataRowView;
//check the value and change the panel visibility
if (row["Maskine_Type"].ToString() == "myValue")
{
panel.Visible = true;
}
}
To check for NULL values you have to use a ternary operator.
<%# !string.IsNullOrEmpty(Eval("Maskine_Type").ToString()) ? Eval("Maskine_Type").ToString().Substring(0, Eval("Maskine_Type").ToString().Length - 2) : "Field is empty" %>

Nesting Repeater Throws Casting Error

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" %>

How to access Parent repeater id from code behind

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

how to get value by index and not by column name in asp:repeater #Eval

I am trying to get the data using column index and not the column name using the <%#Eval('foo')%> expression (or any other way) in my repeater control.
here are my codes :
page :
<asp:Repeater ID="rptrHeatingNavien" runat="server">
<ItemTemplate>
<li class="icon-font"><a href="/Products/?Id=<%#Eval('get-data-by-index[0]')%>><a><%#Eval('get-data-by-index[1]')%></a></li>
</ItemTemplate>
</asp:Repeater>
code-behind:
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Products", sqlCon);
DataSet ds = new DataSet();
sqlDa.Fill(ds);
rptr.DataSource = dsSideMenu.Tables[0].Select("category = '1-1-1'");
rptr.DataBind();
the problem here is that for some reason(I'd be more than happy to know why), I cannot use column names for the rows that I am binding to my repeater control.(And I double checked that they actually have the data in them).So the only solution that is in front of me is to get them by their column indexes, and I have no idea how I can do it.Any solutions?
Assuming that you are binding a collection of SuperItem objects (SuperItem type supports index-based access) you can handle ItemDataBound event:
<asp:Repeater ID="rptrHeatingNavien" runat="server" OnItemDataBound="rptrHeatingNavien_ItemDataBound">
<ItemTemplate>
<li class="icon-font">
<asp:HyperLink runat="server" ID="productLink" />
</ItemTemplate>
</asp:Repeater>
Code-behind:
protected void rptrHeatingNavien_ItemDataBound(object sender, EventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var item = (SuperItem) e.Item.DataItem;
var link = (HyperLink) e.Item.FindControl("productLink");
link.NavigateUrl = string.Format("/Products/?Id={0}", item[0].ToString());
link.Text = item[1].ToString();
}
}

dropdown list does not let select items properly

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.

Categories

Resources