Set AlternateItemTemplate Manually - c#

Is there a way to set AlternateItemTemlate manually?
I suffered from this question more than once.
I want to use it only for the last item.
Maybe ItemDataBound event can be a solution but i can not figured out.
Only useful questions that I've found:
Is there a similar way to AlternateItemTemplate to do this
How can i get last record value from repeater control.?

The ItemDataBound is indeed a possible option, but for it to work, you would need the total count of the repeater items, so you can identify the last item:
protected void rptDummy_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
int itemsCount = ((List<SomeClass>)rptDummy.DataSource).Count;
if (e.Item.ItemType == ListItemType.Item)
{
if(e.Item.ItemIndex == itemsCount - 1)
{
//Do Things here
}
}
}
You could even have two placeholders within the same template, one specially for the last item:
<ItemTemplate>
<asp:PlaceHolder id="phIsNotLastOne" runat="server">Is not last</asp:PlaceHolder>
<asp:PlaceHolder id="phIsLastOne" runat="server">Is last</asp:PlaceHolder>
</ItemTemplate>
Then you could do something like this:
protected void rptDummy_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
long itemsCount = ((List<SomeClass>)rptDummy.DataSource).Count;
if (e.Item.ItemType == ListItemType.Item)
{
PlaceHolder phIsLastOne = (PlaceHolder)e.Item.FindControl("phIsLastOne");
PlaceHolder phIsNotLastOne = (PlaceHolder)e.Item.FindControl("phIsNotLastOne");
phIsLastOne.Visible = e.Item.ItemIndex == itemsCount - 1;
phIsNotLastOne.Visible = !this.phIsLastOne.Visible;
}
}

Related

Remove ddl's that has no value's

I have little problem. I'm dynamically populating grid view from the values from the database. I'm trying to remove DropDownList's that don't have any values.
I have this code for now:
if (ddlMyDropDown.Items.Count == 0)
{
ddlMyDropDown = false;
}
else
{
ddlMyDropDown = true;
}
<asp:TemplateField HeaderText="Opis">
<ItemTemplate>
<asp:DropDownList ID="ddlMyDropDown" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
This code works fine but it has one problem. It doesn't remove first ddl in column who is also empty but it removes every other after.
Is there any way to select first ddl who si dinamically loaded in the column and set it to visible false ?
Or some foreach loop that eliminates the ddl's with empty value better ?
Can someone help me ?
Thanks in advance !
You can do this.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl =e.Row.FindControl("ddlMyDropDown") as DropDownList;
if (ddl.Items.Count == 0)
{
ddl.Visible = false;
}
else
{
ddl.Visible = true;
}
}
}

Show the page with particular item in RadGrid

I have a RadGrid that I supply with data using DataSourceID. The RadGrid has paging, and I want to show the page containing some particular item. To do this, I find the offset of the item in the data and set the page number:
var index = dataSource.Count(t => t.Id > _selectedTickId);
var page = index / rgTicks.PageSize;
rgTicks.CurrentPageIndex = page;
My question is where to put this code. In the OnDataBound I don't seem to have access to the data source. If I put it in the OnSelecting the retrieving of data has a side effect of setting the page number. Should I extend the GridTableView to implement this functionality? Which method should I override?
I will suggest to compute index value in OnSelecting (which is data dependent) while page index can be set in OnDataBound or PreRender event.
My usecase was to jump to an item that was just inserted using a popup editor. Here's how I solved it. I am omitting non relevant properties in the tag. All the data wiring is up to you, but here are the relevant bits. Important: use DataKeyNames to avoid messy digging in the GridDataItem for a value.
In the page I have:
<telerik:RadGrid ID="rgItems" runat="server" AllowPaging="true"
OnNeedDataSource="rgItems_NeedDataSource"
OnPreRender="rgItems_PreRender"
OnInsertCommand="rgItems_InsertCommand">
<MasterTableView
CommandItemDisplay="Top"
CommandItemSettings-AddNewRecordText="Add New Item"
CommandItemSettings-ShowAddNewRecordButton="True"
DataKeyNames="IntItemId"
EditMode="popup"
EditFormSettings-PopUpSettings-Modal="true">
And in code behind:
private bool itemInserted = false;
protected void rgItems_InsertCommand(object sender, GridCommandEventArgs e)
{
itemInserted = true;
}
protected void rgItems_PreRender(object sender, EventArgs e)
{
if (itemInserted)
{
// Select the record and set the page
int LastItem = 0; // Put code to get last inserted item here
int Pagecount = rgItems.MasterTableView.PageCount;
int i = 0;
GridDataItem GDI = null;
while (i < Pagecount)
{
rgItems.CurrentPageIndex = i;
rgItems.Rebind();
GDI = rgItems.MasterTableView.FindItemByKeyValue("IntItemId", LastItem);
if (GDI != null) break; // IMPORTANT: Breaking here if the item is found stops you on the page the item is on
i++;
}
if (GDI != null) GDI.Selected = true; // Optional: Select the item
itemInserted = false;
}
}

Getting total for a column in ListView

I need to get a sum for all items in a column within a listview. I put in the following code in the itemdatabound event, but realized after testing it that it will only be getting what is bound, oops.
So I was looking for a little help converting this to show a total for my column from all items bound to the ListView.
Thanks.
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem item = (ListViewDataItem)e.Item;
Label lblQty = (Label)e.Item.FindControl("lblQuantity");
if (lblQty == null)
{
return;
}
if (lblQty.Text.Length == 0 || lblQty.Text == "")
{
return;
}
else
{
ListViewTotal += int.Parse(lblQty.Text);
}
}
The best method I have found to do this is to implement the OnDataBinding method for the control you are binding. For example:
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<asp:Literal ID="yourLiteral" runat="server"
OnDataBinding="yourLiteral_DataBinding"></asp:Literal>
</ItemTemplate>
</asp:ListView>
First define a global counter in your .cs:
private int _quantityTotal = 0;
Then implement the OnDataBinding for the control:
protected void yourLiteral_DataBinding(object sender, System.EventArgs e)
{
// You could get anything here to get a value including calling a DB
// call if you want for each item that is being bound.
Literal lt = (Literal)(sender);
int quantity = (int)(Eval("yourQuantityField"));
_quantityTotal += quantity;
lt.Text = quantity.ToString();
}
Now you have the total stored in _quantityTotal which you can then add to a footer or something else after the databinding has occurred like the OnDataBound event.
Yes, you will have to query the DB to get this value, or depending on what you are binding, loop through the collection you are binding and sum the values from the classes or DataSet/DataTable you are binding to it.
HTH.

How to get the bound item from within an ASP.NET repeater

I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)

Update label C#

When the page first load i have a label who has 0 or 1. Look at the code and you will se what i trying to do. But it don't work because the page allready loaded.
protected void rptBugStatus_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lblName = e.Item.FindControl("lblBugStatus") as Label;
if (lblName.Text == "1")
{
lblName.Text = lblName.Text + "Under arbete";
}
else if (lblName.Text == "0")
{
lblName.Text = "Fixad";
}
else { }
}
}
You really want to avoid this type of coding if at all possible. This will quickly grow into an unmaintainable web site.
Query the underlying data instead of GUI elements.
where you put your code? and be cautious e.Item.FindControl("lblBugStatus") as Label; may return null
it's just work fine to fine the control. But i figure out another way to get out the data i want. That i'am going to is fix the xml structur better.
You may have resolved this by now, but I think the problem with the code as you posted it is this:
Label lblName = e.Item.FindControl("lblBugStatus") as Label;
Because you are referencing a control in a repeater, the controls inside each repeater item are named dynamically based on their context. Most likely the name of the control is something like:
"rptBugStatus$repeaterItem0$lblBugStatus"
To find out the exact name, hard code a value, run the page in a browser, and look at the HTML output (via "View Source" in the browser menu). You should be able to scroll down and see your repeater (it will be rendered as a <table> tag), its items, and the controls living inside each item. The IDs/Names will be set and you can copy/paste them into your FindControl method.
Hope this helps,
Nate
Ok, I am taking the assumption you have set this label (assuming to be in the repeater, from your code) to have a value - I have tried databinding to something exactly the same, using the below code.
protected override void OnPreRender(EventArgs e)
{
base.OnLoad(e);
List<string> strList = new List<string>();
strList.Add("1");
rptBugStatus.DataSource = strList;
rptBugStatus.DataBind();
}
protected void rptBugStatus_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lblBugStatus = e.Item.FindControl("lblBugStatus") as Label;
// have added this just so we are actually setting the text property on the bug status
// - i have assumed you do this.
lblBugStatus.Text = e.Item.DataItem.ToString();
if (lblBugStatus.Text.Equals("1"))
{
lblBugStatus.Text = lblBugStatus.Text + "Under arbete";
}
else if (lblBugStatus.Text.Equals("0"))
{
lblBugStatus.Text = "Fixad";
}
}
}
With the aspx being
<asp:Repeater runat="server" ID="rptBugStatus" OnItemDataBound="rptBugStatus_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblBugStatus" runat="server"></asp:Label>
</ItemTemplate>
</asp:Repeater>
And I have no problems.
I get the below on the page.
1Under arbete
I think you are going to need to post more code if you have hidden any away from us :)
Tim

Categories