I'm currently having a problem in displaying some stuff in ListView. I have a normal C# Student class and a Classroom class. In Classroom class contains a List of Student classes which is shown below:
public class Classroom
{
int classroomid {set;get;}
List<Students> students{set;get;}
}
My question is if I bind my DataSource of the ListView to a List of objects of Classroom, how do I render the Student lists in the ListView?
<ListView>
<ItemTemplate>
<asp:Label Text='<%# Eval("classroomid") %>'></asp:Label>
<asp:Label Text='<%# Eval("students") %>'</asp:Label>
<asp:Label Text='<%# Eval("students.name") %>'</asp:Label>
</ItemTemplate>
</ListView>
The code above essentially explains that what I'm trying to achieve, or possibly displays the student's details such as name or etc. Is there any way to achieve that? I do understand that nested ListView works, but I'm not sure how is the implementation.
Thank you for your help in advance. :-)
You could use string.Join:
<asp:Label runat="server" ID="LblStudents"
Text='<%# string.Join(",", (List<string>)Eval("students")) %>'>
</asp:Label>
Edit: I missed that Student is a custom type. So you should better do this in the ListView's ItemDataBound event for readability.
But it should work also on aspx:
<asp:Label runat="server" ID="LblStudents"
Text='<%# string.Join(",", ((List<Student>)Eval("students")).Select(s=>s.Name)) %>'>
</asp:Label>
in codebehind:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label LblStudents = (Label)e.Item.FindControl("LblStudents");
Classroom cr = e.Item.DataItem as Classroom;
if (cr != null && cr.students != null && cr.students.Count > 0)
{
LblStudents.Text = string.Join(",", cr.students.Select(s => s.Name));
}
}
}
Related
I have a Linq query:
var result = from p in db.Messages
join c in db.Students on p.Stud_Id equals c.Stud_Id
where (p.Staff_Id == Int32.Parse(userID.Text))
select new
{
c.Stud_Id,
c.FirstName,
p.BySupervisor
};
How can I add result to list and binding each value in Lable using DataBinder. Of course, i have already repeater control to databound
Try like this
Create a class
public class stud
{
public int Stud_Id {set;get;}
public string FirstName{set;get;}
public string BySupervisor {set;get;}
}
Then convert dataset into that class's list
var result = (from p in db.Messages
join c in db.Students on p.Stud_Id equals c.Stud_Id
where (p.Staff_Id == Int32.Parse(userID.Text))
select stud
{
Stud_Id=c.Stud_Id,
FirstName=c.FirstName,
BySupervisor=p.BySupervisor
}).ToList<stud>();
Then bind data with repeater
repeaterControl.DataSource = result ;
repeaterControl.DataBind();
If you already have included the Repeater control(as per your comment) then simply assign the datasource like this:-
YourrepeaterControlId.DataSource = result;
YourrepeaterControlId.DataBind();
Please note there is No Need to materialize your result into a List<T>, it will work just fine if you pass IEnumerable<T>.
Thus in your case suppose your control looks like this:-
<asp:Repeater ID="YourrepeaterControlId" runat="server">
<ItemTemplate>
<asp:Label ID="StudIdLabel" runat="server" Text='<%# Eval("Stud_Id") %>'>
</asp:Label>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>'>
</asp:Label>
<asp:Label ID="lSupervisor" runat="server" Text='<%# Eval("BySupervisor") %>'>
</asp:Label>
</ItemTemplate>
</asp:Repeater>
Binding your control as I mentioned earlier will work just fine, there is no need to create an extra class.
with asp.net c# I get the code of a country with bind :
<asp:Label runat="server" Text='<%# Bind("h_country") %>' ID="Label1"></asp:Label>
this return code of country like usa, tr, eg, il.
I need to put if conditions and I try to do it like this:
<asp:Label runat="server" Text='<%# if(Bind("h_country")=="usa") resonse.write("United States"); %>' ID="Label1"></asp:Label>
note: I'm using GridView and template.
I tried alo at code behind to get the value of country like this:
String s = Lable1.Text;
but also not workes!
how can I get it as a variable and use if condition ?
You need to use find control if thus label is within the gridview and then get the sting from label.
You probably want to handle this in the code behind
<asp:Label runat="server" Text='<%# GetCountry(Eval("h_country")) %>' ID="Label1"></asp:Label>
code behind
public string GetCountry(object country)
{
if (county.ToString() == "usa")
return "United States";
}
It would be better if you had a lookup so you don't have to have a lot of if statements
This is how you can do conditional checks in the markup while binding. Try something like below but I would not advise doing this kind of conditional checks and response.write at the template level but do it in code behind.
<asp:Label runat="server" Text='<%# Bind("h_country") == "usa" ? "United States" : (string)Bind("h_country") %>' ID="Label1"></asp:Label>
And this is how you can do it at code behind. Use the databound event to find the Label1 and set the appropriate text in there.
You need to define OnRowDataBound="gvTest_DataBound for the gridview in the markup
protected void gvTest_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblCountry = (Label)e.Row.FindControl("Label1");
if (lblCountry.text == "usa"){
// do something here
}
else {
// do something otherwise
}
}
}
Im trying to learn asp and C# and trying to make a webshop.
I have a working dataset and datalist
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="ObjectDataSource1" RepeatDirection="Horizontal" CellSpacing="10">
<ItemTemplate>
<asp:Image ImageUrl='<%# Eval("PicURL") %>' runat="server" ID="PicURLImage" Width="150px" /><br />
<asp:LinkButton ID="AddProduct" Text='<%# Eval("ProductName") %>' runat="server" OnClick="AddProduct_Click"></asp:LinkButton><br />
</ItemTemplate>
</asp:DataList>
I want to press this linkbutton and then It eventually should add this product to a shoppingcart. But right now I just need help to get the selected product row from the datalist that is using a datasource that is connected to the database.
When I click the link I want to execute this code:
Data.DataSet1.ProductDataTable pTable = new Data.DataSet1TableAdapters.ProductTableAdapter().GetDataByCategory();
protected void AddProduct_Click(object sender, EventArgs e)
{
// Add product to the shopping cart
//Class //method
ShoppingCart.Instance.AddItem(THIS IS HE QUESTION I NEED HELP WITH!);
// Redirect the user to view their shopping cart
Response.Redirect("ViewCart.aspx");
}
public void AddItem(int productId)
{
// Create a new item to add to the cart
CartItem newItem = new CartItem(productId);
// If this item already exists in our list of items, increase the quantity
// Otherwise, add the new item to the list
if (Items.Contains(newItem))
{
foreach (CartItem item in Items)
{
if (item.Equals(newItem))
{
item.Quantity++;
return;
}
}
}
else
{
newItem.Quantity = 1;
Items.Add(newItem);
}
}
Do you guys need more information? Do you have any tips or suggestions? Im stuck >__<
Here is how I would do this.
add CommandName attribute to your button (you will not longer need the OnClick event handler for the button) and add event handler for ItemCommand on DataList:
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="ObjectDataSource1" RepeatDirection="Horizontal" CellSpacing="10" OnItemCommand="Item_Command">
<ItemTemplate>
<asp:Image ImageUrl='<%# Eval("PicURL") %>' runat="server" ID="PicURLImage" Width="150px" /><br />
<asp:LinkButton CommandName="AddProduct" ID="AddProduct" Text='<%# Eval("ProductName") %>' runat="server" OnClick="AddProduct_Click"></asp:LinkButton><br />
</ItemTemplate>
</asp:DataList>
Change your c# to define Item_Command
void Item_Command(Object sender, DataListCommandEventArgs e)
{
if (e.CommandName == "AddProduct")
{
// e.Item.ItemIndex is the selected index
// DataList1.DataKeys[e.Item.ItemIndex] will return the product id
}
}
Also you can refer to MSDN for further details.
protected void Btn_Command(object sender, CommandEventArgs e)
{
DataListItem dli = (DataListItem)(sender as Control).Parent.Parent;
int indx = dli.ItemIndex;
}
I am building a website whereby people, before checking out of the shopping cart (and transferring to the payment iframe) can select which items from the shopping cart list to delete. The results from the shopping card are listed in a Repeater control. There is a Button in the Repeater which deletes a record from the database (used LINQ to SQL to do that.)
The problem is that the ItemCommand event doesn't fire when i click the button. I tried response.write(test) and it still would not work.
It is as if the repeater cannot interact with the commands. It does render the results though.
<asp:Repeater ID="RepeaterKoshnichka"
runat="server" OnItemCommand="RepeaterKoshnichka_ItemCommand"
DataSourceID="LinqDataSource1">
<ItemTemplate>
<tr>
<td background="images/message-bar.gif">
<div class="message_head" style="float:left"><cite>Производ: <asp:Label ID="lblProizvod" CssClass="red_tx" Text='<%# Eval("Proizvod") %>' runat="server"></asp:Label> / Тип на Претплата: <asp:Label ID="lblPretplata" runat="server" Text='<%# Eval("Tip") %>' CssClass="red_tx"></asp:Label></cite></div>
<div class="message_head" style="float:right"><cite>Цена: <asp:Label ID="lblCena" CssClass="red_tx" Text='<%# Eval("Cena") %>' runat="server"></asp:Label>
<asp:Button ID="Button2" CssClass="main_tx" CommandName="Delete" CommandArgument='<%# Eval("NDetID") %>' runat="server" Text="Отстрани" /></cite>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
protected void RepeaterKoshnichka_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
if (Request.Form[e.CommandArgument.ToString()] != null)
{
if (Page.User.Identity.IsAuthenticated)
{
var nar = new DataClasses1DataContext();
Guid detnar = new Guid(e.CommandArgument.ToString());
var query = from c in nar.Naracka_Dets
where c.NDetID == detnar
select c;
foreach (var c in query)
{
nar.Naracka_Dets.DeleteOnSubmit(c);
}
nar.SubmitChanges();
lblSuma.Text = ((Button)e.CommandSource).ToString();
}
}
}
}
Likely an <asp:GridView> would be a better server control for what you're working on.
As an aside, consider making a small change to your code. To help make it more readable, combine your 3 conditions into one if:
if (e.CommandName == "Delete" &&
Request.Form[e.CommandArgument.ToString()] != null &&
Page.User.Identity.IsAuthenticated)
{
//delete things.
}
If you are not tied to using a Repeater you should switch to DataGrid and use a ButtonColumn for this feature - it will make life easier for you handling Item events.
I would like to run an if statement but the condition uses a variable from the code behind. How do I call that variable? Side note... I am using a gridview and the variable is in a dataset (dsResult - idnbr colum)
<ItemTemplate>
<% string temp = (Eval("idnbr").ToString());
if (temp.Contains("X")) { %>
<asp:Label ID="Label1" runat="server" Text='<%# (Eval("old_amt").ToString(),"ccTot") %>'></asp:Label>
<% } else { %>
<asp:Label ID="Label2" runat="server" Text='<%# (Eval("new_amt").ToString(),"ccTot") %>'></asp:Label>
<% } %>
</ItemTemplate>
Create c# side method that does it for you:
Than use one of 2 ways:
If you deal with well known entity (saying when GridView bound to ObjectDatasource) you
can just cast it to your entity and pass back:
C#:
protected String MySelectorImpl(Object rowData)
{
MyEntity ent = (MyEntity)rowData;
if(ent.idndr .... )
return ....
else
return ...
}
ASP.Net:
<ItemTemplate>
<asp:Label Text='<%# MySelector(Container.DatatItem) %>' ...
Second case - just use eval syntax
C#:
protected string MySelector(Object condition, Object value1, Object value2)
{
if((String)condition ....) return value1.ToString ....
}
ASP.Net:
<ItemTemplate>
<asp:Label Text='<%# MySelector(Container.DatatItem("idnbr", ... %>' ...
(,
I know this doesn't completely answer your question but why not just do this in the code behind? I'm assuming you're doing something with DataBinding?
string temp = (string)DataBinder.Eval(e.Item.DataItem, "idnbr");
string newAmount = (string)DataBinder.Eval(e.Item.DataItem, "new_amt");
string oldAmount = (string)DataBinder.Eval(e.Item.DataItem, "old_amt");
Label lbl1 = e.Item.FindControl("label1") as Label;
if(temp.Contains("X") {
lbl1.Text = oldAmount;
} else {
lbl1.Text = newAmount;
}
You can read from a property that is declared in the code behind; does this satisfy what you want?
Instead of string temp = ..., you can use this.MyProperty.Contains("X")...
<a href="javascript:onclick= window.location = 'RenewalPaymentGateway.aspx?RPID=<%# Eval("RPID")%>'" title="Pay">
<asp:Label ID="TEMP" Text='<%# If(Eval("PaymentStatus").ToString() = "Paid", "View", "Make payment") %>' runat="server" />
here in label the text view will appear when PaymentStatus=paid or the text will be make payment