Get subitem value in radlistview items - c#

here is my listview
<telerik:RadListView runat="server" ID="lvAllUsers" Width="30px">
<ItemTemplate>
<table>
<tr>
<td >
<asp:CheckBoxList ID="cbID" runat="server" CssClass="item" Font-Size="15px" RepeatDirection="Horizontal">
<asp:ListItem Text=" " > </asp:ListItem>
</asp:CheckBoxList></td>
<td style="padding-bottom:10px"><%# Eval("FirstName") %></td>
<td style="padding-bottom:10px"><%# Eval("FamilyName") %></td>
</tr>
</table>
</ItemTemplate>
</telerik:RadListView>
how can I get checkboxlists item text at code behind ? or how can I get FirstName and FamilyName and code behind after I binded my data at pageload?
I can't use
foreach (Telerik.Web.UI.RadListViewItem item in lvAllUsers.Items) {
var cb = item.FindControl(index);
}
because index is equals an id normally. But in item template id is not equal to cbID. When item template iteratives, id is changing. I need get FirstName and FamilyName or checkboxlists item at codebehind (c# only not js). How can I do that?

I find the solution. It's seems like a little long way but it works.
foreach (Telerik.Web.UI.RadListViewItem item in lvAllUsers.Items)
{
if (((System.Web.UI.WebControls.CheckBoxList)(((System.Web.UI.Control)(item)).Controls[1])).Items[0].Selected)
{
ccUserNames.Add(((System.Web.UI.WebControls.Label)(((System.Web.UI.Control)(item)).Controls[7])).Text);
}
}

Related

ListView DataBind Sorting Values

I want to have a DropdownMenu from which i can choose how i want to sort my ListView.
This is my current code for it :
<asp:DropDownList ID="DropDownSelect" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="GetProducts">
<asp:ListItem Selected="True" Value="DesDate"> Descending Date </asp:ListItem>
<asp:ListItem Value="AsDate"> Ascending Date </asp:ListItem>
<asp:ListItem Value="AsAlp"> Ascending Alphabetical </asp:ListItem>
<asp:ListItem Value="DesAlp"> Decentind Alphabetical </asp:ListItem>
</asp:DropDownList>
And I have this ListView to display my data:
<asp:ListView ID="productList" runat="server"
DataKeyNames="NewsID" GroupItemCount="1"
ItemType="SiteStiri.Models.News" SelectMethod="GetProducts">
<EmptyDataTemplate>
<table>
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<EmptyItemTemplate>
<td/>
</EmptyItemTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server"></td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td runat="server">
<table>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<img src="/Catalog/Images/Thumbs/<%#:Item.ImagePath%>"
width="100" height="75" style="border: solid" /></a>
</td>
</tr>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<p style="color: black;">
<%#:Item.NewsTitle%>
</p>
</a>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</p>
</td>
</ItemTemplate>
<LayoutTemplate>
<table style="width:100%;">
<tbody>
<tr>
<td>
<table id="groupPlaceholderContainer" runat="server"
style="width:100%">
<tr id="groupPlaceholder"></tr>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr></tr>
</tbody>
</table>
</LayoutTemplate>
</asp:ListView>
The thing that i have no idea how to do is:
After selecting a sorting rule from the dropdown menu, i can't figure out how to write(or where to write) the method that would update my ListView as it should. My attemp is :
public IQueryable<News> GetProducts()
{
var _db = new SiteStiri.Models.NewsContext();
IQueryable<News> query = _db.News;
if (("DesDate").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderByDescending(u => u.ReleaseDate);
}
if (("AsDate").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderBy(u => u.ReleaseDate);
}
if (("AsAlp").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderBy(u => u.NewsTitle);
}
if (("DesApl").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderByDescending(u => u.NewsTitle);
}
return query;
}
which gives me a bunch of errors and it doesn't even work .... a little bit of help please? I am new to this (2 days).
Let's fix your code step by step.
Event handlers need to have a certain signature. In case of every ASP.NET control I can remember of, they need to receive two parameters, event arguments and event source object, and return void. Also note that just calling GetProduct is not going to update ListView, we need to trigger databinding for the control itself. We'll get to that later. For now let's introduce a proper handler:
public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e)
Don't forget to update markup as well:
OnSelectedIndexChanged="DropDownSelect_SelectedIndexChanged"
The conditions on how you show data in the ListView have changed. That means that you need to rebind it with calling DataBind, which should call GetProducts (as a one specified in SelectMethod):
public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e)
{
productList.DataBind();
}
Finally in GetProducts note that LINQ calls do not update the current object, but rather they produce new one every time. So you should have something like this:
if ("DesDate".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderByDescending(u => u.ReleaseDate);
}
I am guessing you want the data and not the query right? That code would look like this, all you have to do is parse the selected value and pass it into the method. If the ListView is bound to the data (and it should be) you're all set. This example shows the separation of concerns, whereby the view is just a framework for HOW to show the data, and the code behind is a framework for WHAT data is supplied based on triggers from the view. The trigger in this case is the "filter" parameter.
List<News> query = _db.News.ToList();
public List<News> GetProduct(string filter) {
if (filter == "DesDate") return query.OrderByDescending(u => ReleaseDate).ToList();
}
One last note: IQueryable is a class that lets you pass queries around, you can alter the query itself from method to method. But this class does not produce results until it is told to do so by using any of the To methods like ToList(), ToArray(), ToLookup() and or any attempt to iterate over it such as:
Foreach(var thing in MyQuerable){ //results are here }

ASP.NET how to change background color of table row on button click + row entry?

I have a table with one row which is filled in with values after the user clicks a button. I want to change the background color of the row to different colors based on the values that are filled in to the row.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" />
<tr>
<td runat="server" id ="td1" class="auto-style1"></td>
<td runat="server" id ="td2" class="auto-style1"></td>
<td runat="server" id ="td3" class="auto-style1"></td>
<td runat="server" id ="td4" class="auto-style1"></td>
</tr>
and my Button1_Click function looks like
protected void Button1_Click(object sender, EventArgs e)
{
string[]toDisp = someFunction();
td1.InnerText = toDisp[0];
td2.InnerText = toDisp[1];
td3.InnerText = toDisp[2];
td4.InnerText = toDisp[3];
}
Basically, I want to set the background color of the table row based on the value of toDisp[1]. How should I go about doing this? Thanks.
If its going to be just 1 row
just set a ID to it with runat attribute
<tr id="test" runat="server">
<td runat="server" id ="td1" class="auto-style1"></td>
<td runat="server" id ="td2" class="auto-style1"></td>
<td runat="server" id ="td3" class="auto-style1"></td>
<td runat="server" id ="td4" class="auto-style1"></td>
</tr>
then based on the condition of toDisp[1]
you can write a switch statement or Random (based on color requirement) to just set
test.BgColor = "SomeColor";

Build Listview from Code behind

I have a large table that can have many null, empty or false columns. I only want to show the columns that are worth showing.
Here is a sample of the query and how I am trying to build up the listview:
var query = (from q in db.tblIncidents
where q.Id == searchQuery
select new
{
q.victim,
q.reportedByVictimPostCode
}).ToList();
lst_Results.DataSource = query;
lst_Results.DataBind();
foreach (var colitem in query)
{
if (!colitem.victim == false)
{
** Help required here please **
lst_Results.Items.Add(new ListViewDataItem(0,1));
}
}
I did start off building my list view on the aspx page, but realised that the result would be lots of empty fields and a waste of time for the user seeing nothing if the user hadn't entered any thing.
What I want to do is achieve this but in the code behind by querying if there is a result to display.
<ItemTemplate>
<tr>
<td>Incident Id:</td>
<td>
<asp:Label ID="lbl_CustomerId" runat="server" Text='<%# Eval("Id") %>' />
</td>
</tr>
<tr>
<td>Reported by the Victim:</td>
<td>
<asp:Label ID="lbl_victim" runat="server" Text='<%# Eval("victim") %>' />
</td>
</tr>
</ItemTemplate>
Would I use something like so?
lst_Results.InsertItem.DataItem(colitem.victim);
Which I get the error method delegate or event expected?
Does it know to insert into the listItem template?
I have a layout template with the itemPlaceholder. The listview works ok just want to target it from code behind.

textbox not displaying in code behind c# file

I have a sales simulator written in C#. I did not write this however I am currently modifying it to suit different requirements.
It basically displays a list of products from a database, and has a textbox for each product where you can enter in the quantity sold. The quantity sold is calculated based on it's price in the database.
Now it's all working fine, however there is one SMALL issue. When "Buy" is clicked, it returns me back to the list of products which IS correct, however the quantity I have entered for the previous product remains.
I would like to know how to restore the text boxes to their default value when the after the data is submitted to the database.
I always thought the way to do this would be in the .cs code behind file
txtQuantity.Text = "";
However, for some odd reason, txtQuantity will not show up.
Can anyone think of anything I am doing wrong? Here is a snippet of code from the aspx file.
<form id="form1" runat="server">
Date:
<asp:TextBox ID="txtDate" runat="server" />
Retailer:
<asp:DropDownList ID="dlStore" runat="server"
onselectedindexchanged="dlStore_SelectedIndexChanged" />
<asp:ListView ID="lbProducts" runat="server">
<LayoutTemplate>
<layouttemplate>
<table border="1" cellpadding="1" style="width:800px">
<tr style="background-color:#E5E5FE">
<th>ID</th>
<th>ProductCode</th>
<th>Product Title</th>
<th>RRP $</th>
<th>Quantity</th>
<th>Sale Price $</th>
</tr>
<tr id="itemPlaceholder" runat="server"></tr>
</table>
</layouttemplate>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td style="width: 50px;">
<%#Eval("ProductID") %>
</td>
<td>
<%#Eval("ProductCode") %>
</td>
<td>
<%#Eval("ProductTitle") %>
</td>
<td>
<%#Eval("USListPrice") %>
</td>
<td style="width: 50px;">
<asp:TextBox ID="txtQuantity" runat="server" Text="0" />
</td>
<td style="width: 50px;">
<asp:TextBox ID="txtSalePrice" runat="server" Text="0.00" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btnBuy" Text="Buy These Items" runat="server" OnClick="btnBuy_Click" />
<asp:Button ID="btnClear" Text="Clear Existing Sales" runat="server"
onclick="btnClear_Click" />
</form>
There's a lot going on in the code behind file and I wouldn't expect anyone to go through it, but how I collect the data from txtQuantity is done with the following line of code:
Int32 quantity = Int32.Parse(((TextBox)item.FindControl("txtQuantity")).Text);
So what I want to be able to do is set this textbox either to be empty, or back to zero.
Any help is appreciated, thanks.
Because that txtQuantity control is within a ListView, there could be any number of instances of that control generated. So you can't access all of them through a single variable.
You will need to look through all controls within that ListView (and several levels deep) to find all your txtQuantity controls.
The same of course for the txtSalePrice control.
EDIT
You could find those textboxes with code like (untested)
public IEnumerable<TextBox> FindTextBoxes(Control parent)
{
if (parent == null) yield break;
foreach (Control child in parent.Controls)
{
TextBox tb = child as TextBox;
if (tb != null)
yield return tb; // found one!
else
foreach(TextBox tb in FindTextBoxes(child))
yield return tb; // found it deeper
}
}
and call it like:
foreach(TextBox tb in FindTextBoxes(lbProducts)
{
if (tb.Name == "txtQuantity")
{
// found a quantity
}
else if (tb.Name == "txtSalePrice")
{
// found the salesprice
}
}

How can I set a table row color in my repeater based on the values databound to that row in ASP.NET?

I have a repeater control:
<table style="width: 100%">
<asp:Repeater runat="server" ID="rptOptions" OnItemDataBound="rptOptions_ItemDataBound">
<HeaderTemplate>
<tr>
<td class="GridHeader">Account</td>
<td class="GridHeader">Margin</td>
<td class="GridHeader">Symbol</td>
<td class="GridHeader">Price</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td class="GridRow"><asp:Label runat="server" ID="lblOptionAccount"></asp:Label></td>
<td class="GridRow"><asp:Label runat="server" ID="lblOptionMargin"></asp:Label></td>
<td class="GridRow"><asp:Label runat="server" ID="lblOptionSymbol"></asp:Label></td>
<td class="GridRow"><asp:Label runat="server" ID="lblOptionPrice"></asp:Label></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
And the following code-behind databound method:
protected void rptOptions_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Option rowOption = (Option)e.Item.DataItem;
((Label)e.Item.FindControl("lblOptionAccount")).Text = rowOption.Account;
((Label)e.Item.FindControl("lblOptionMargin")).Text = rowOption.Margin ? "Y" : "N";
((Label)e.Item.FindControl("lblOptionSymbol")).Text = rowOption.Symbol;
((Label)e.Item.FindControl("lblOptionPrice")).Text = rowOption.Price.ToString("C", currencyFormat);
}
}
There are more columns in that grid, but I've slimmed it down just for the question.
Now, what I would like to do is change the tr's background color based on the price amount. If it is within different levels, I would like to change the rows background color correspondingly.
Do I have to do this with javascript or is there some way I can get access to the table rows in the code-behind to set this color?
make it to runat="Server"
<tr runat="server" ID="trHeader"></tr>
Then find that Table Row in by ID in your code behind in databound event, like what you are doing for other server side control and change color.
another option:
<tr class="<%# GetClassForPrice( Container.DataItem ) %>">
and in code-behind
protected string GetClassForPrice( object data )
{
var rowOption = (Option)data;
if(rowOption.Price > 100) return "red";
else return "green";
}
also... any reason you're not using data binding? it would let you eliminate your ItemDataBound code-behind method.
<tr>
<td class="GridRow"><%# Eval("Account") %></td>
<td class="GridRow"><%# ((bool)Eval("Margin")) ? "Y" : "N" %></td>
<td class="GridRow"><%# Eval("Symbol") %></td>
<td class="GridRow"><%# Eval("Price", "{0:c}") %></td>
</tr>
use this code inside repeter databound event.
HtmlTableRow tr = (HtmlTableRow)e.Item.FindControl("trID");
tr.Visible = false;
Another option you can use is jQuery. Seeing you're using a repeater, that gives you full control over your output. Jquery can get into your table, look at the data and format it how you want it.
Look at:
http://plugins.jquery.com/project/Plugins/category/54
http://plugins.jquery.com/project/Colorize
http://franca.exofire.net/js/demo_cross.html
Alternately you can use the Code behind in the repeater to set the CSS Class of the cells/rows/columns you need changed.
You'll need to make those controls server controls (require: ID="my_thing" runat="server"), create those controls (use the find control and bind them), then set the CSS class after you determine the value.
Dave Thieben's answer works nicely, except that the css is missing.
If you add the following then the example will work:
table tr.red td { background-color:red; }
table tr.green td { background-color:green; }

Categories