ASP .NET datalist does not recognize item in ItemDataBound event - c#

I have a datalist and I'm trying to apply a css class to a panel inside some of the items like so:
protected void DataListProducts_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Header)
{
ProductsService service = new ProductsService();
DataTable dt = service.GetProduct(DataListProducts.DataKeys[e.Item.ItemIndex].ToString()).Tables[0];
if (((int)dt.Rows[0]["Quantity"]) <= 0)
{
Panel overlay = (Panel)DataListProducts.Items[e.Item.ItemIndex].FindControl("overlay");
overlay.CssClass = "soldOut";
}
}
}
When I try to run it I get the error
"Index was out of range. Must be non-negative and less than the size
of the collection."
I found out that the item index is equal to the item count of the datalist, which I think means the item hasn't been created yet, but shouldn't the ItemDataBound event fire after the item has been created and databound? Can someone please explain this to me?

Well, kinda solved it. I still don't know what the problem was, but iterating through the datalist with a foreach loop in a different function after the datalist has been databound gives me the desired effect.

Related

ASP.NET How do I check ever row in the gridview?

I want to add value into a Grid view via dropdownlist with a button.
I want the ddTN.SelectedItem.value in the Grid view to be unique. No duplication
How do I check every row for the ddTN.SelectedItem.value before adding a new ddTN.SelectedItem.value into the Grid view?
This are the codes that I have and it keep comparing the value with the first value in the gridview. Not the others.
I don't want to use a checkbox and such. All the example I found required using checkbox.
protected void Insert(object sender, EventArgs e)
{
int i = 0;
var p = 1;
DataControlFieldCell cell = GridView1.Rows[i].Cells[p] as DataControlFieldCell;
if (cell.Text != ddTN.SelectedItem.Value)
{
dt.Rows.Add(ddTN.SelectedValue, ddDuration.SelectedValue);
ViewState["Customers"] = dt;
this.BindGrid();
label.Text = "";
p++;
}
else
{
label.Text = "Exercise already inserted";
}
}
It looks like you were intending on looping over the items in the grid but you have forgotten the looping mechanism. In your code, it always only checks the first item because i is initialized to 0 and never changes.
Try using a looping mechanism like a for loop or a while loop. Or, if you know the items in the grid from the beginning, perhaps use a hash table for quickly checking if the selected item already exists.
Keep trying, you are almost there!

C# Selecting same index on multiple listBox

Okay, so I have four listBox controls. I want to select the same index on all four listBox when one item is clicked on any of them. To be mentioned, I do change the index sometimes in the program. I tryed using a method listSelectChange (int index) and adding for each listBox an event for selectIndexChange, but it would activate the event even if the select is made by the program and not by user-control.
Please don't use classes, just a brute method would be fine!
You can unsubscribe from selectedIndexChanged before you update the ListBox and re-subscribe to it immediately after that. It's a common practice.
Since you gave no code example I'm doing some guessing here.
// Enumerable of all the synchronized list boxes
IEnumerable<ListBox> mListBoxes = ...
...
public void OnSelectedIndexChanged(object sender, EventArgs e) {
var currentListBox = (ListBox)sender;
// Do this for every listbox that isn't the one that was just updated
foreach(var listBox in mListBoxes.Where(lb => lb != currentListBox)) {
listBox.SelectedIndexChanged -= OnSelectedIndexChanged;
listBox.SelectedIndex = currentListBox.SelectedIndex;
listBox.SelectedIndexChanged += OnSelectedIndexChanged;
}
}

Getting subcontrol in Repeater

I am using ASP.NET and C# on .NET 4 to develop a simple app. I have a repeater with an item template containing a few controls; one of them is a label that must be set depending on a complex calculation. I am using the OnItemDataBound event to compute the text and set the label's text in the code behind, like this:
protected void repRunResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//capture current context.
Repeater repRunResults = (Repeater)sender;
Label laMessage = (Label)repRunResults.Controls[0].FindControl("laMessage");
DSScatterData.RunResultsRow rRunResults = (DSScatterData.RunResultsRow)((DataRowView)(e.Item.DataItem)).Row;
//show message if needed.
int iTotal = this.GetTotal(m_eStatus, rRunResults.MaxIterations, rRunResults.TargetLimit);
if(iTotal == 100)
{
laMessage.Text = "The computed total is 100.";
}
else
{
laMessage.Text = "The computed total is NOT 100.";
}
}
The data source for my repeater contains a few rows, so I would expect that each impression of the repeater would call the event handler and show the message according to the data in the associated row. However, I only get one message, which appears on the first repeater impression but matches the data for the last row in the data source.
It seems like every time the ItemDataBound event fires, the controls that my code captures are the same ones, so that I overwrite the message on every impression of the repeater. I have stepped through the code and this is what it is apparently happening.
Any idea why? And how to fix it?
Note. My repeater is nested inside another repeater. I don't think this should be relevant, but it might be.
You are grabbing the first one. You need to use the item that is being passed in like so:
protected void repRunResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//capture current context.
Repeater repRunResults = (Repeater)sender;
Label laMessage = e.Item.FindControl("laMessage"); //<-- Used e.Item here
DSScatterData.RunResultsRow rRunResults = (DSScatterData.RunResultsRow)((DataRowView)(e.Item.DataItem)).Row;
//show message if needed.
int iTotal = this.GetTotal(m_eStatus, rRunResults.MaxIterations, rRunResults.TargetLimit);
if(iTotal == 100)
{
laMessage.Text = "The computed total is 100.";
}
else
{
laMessage.Text = "The computed total is NOT 100.";
}
}

changing checkbox label colour on databound

Ive searched everywhere for this but cant find the answer. I have used the following code before to change repeated items properties in an asp.net repeater as after they have been bound to do things i couldnt do prior to binding them.
protected void rowRepeater_ItemBound(object sender, RepeaterItemEventArgs e)
{
foreach (RepeaterItem item in rptStockists.Items)
{
}
}
Now i am wanting to do something similar but with a chekbox list. i want to change the colour of the labels and i know i can only do this after the list has been bound. I have notice checkboxlists only provide the parameter OnDataBound in intellisense, doesnt give me OnItemDataBound that repeaters do. What would be the equivalent i could use here?
Well, you can use that DataBound event like:
protected void cbl_DataBound(object sender, EventArgs e)
{
foreach (ListItem item in cbl.Items)
{
}
}

DropdownList.selectedIndex always 0 (yes, I do have !isPostBack)

(Scroll down to bottom of post to find solution.)
Got a asp.net page which contains a
Datalist. Inside this datalist, there
is a template containing a
dropdownlist and each time the
datalist is filled with an item, a
ItemCreatedCommand is called. The
itemCreatedCommand is responsible for
databinding the dropdownlist.
I think the problem lies here, that
I'm using ItemCreatedCommand to
populate it - but the strange things
is that if I choose the color "green",
the page will autopostback, and I will
see that the dropdown is still on the
color green, but when trying to use
it's SelectedIndex, I always get 0...
protected void DataListProducts_ItemCreatedCommand(object
source, DataListItemEventArgs e)
var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex];
var item = itemBLL.GetFullItem(itemId);
var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor");
//Also tried with :
//if(!isPostBack) {
DropDownListColor.DataSource = item.ColorList;
DropDownList.Color.Databind();
// } End !isPostBack)
Label1.test = DropDownListColor.SelectedIndex.toString();
// <- THIS IS ALWAYS 0! *grr*
I've narrowed down the code a bit for
viewing, but still you can see what
I'm trying to do :) The reason for
why I'm doing this, and not declaring
the datasource for the colors directly
i aspx-page, is that I need to run a
test if(showColors), but I do not want
to clutter up the html-page with code
that I feel should be in the code
behind-file.
EDIT: After trying to alter
SelectedIndexChange - I'm having a
"logical" confusion in my head now -
how am I to alter elements inside the
datalist? Since, as far as I know - I
do not have any way to check which of
the items in the datalist this
particular dropdownlist belongs to...
Or? I'm going to try out a few ways
and see what I end up with ;) But do
please post your thoughts on this
question :)
SOLUTION:
Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there.
protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
var item = items[dataListItem.ItemIndex];
var color = item.ItemColor[dropDownListColor.SelectedIndex];
var LabelPrice = (Label)dataListItem.FindControl("LabelPrice");
LabelPrice.Text = color.Price;
}
When the DataList is data-bound, the AutoPostBack has not been handled yet, i.e. the values in the ItemCreated event are still the original values.
You need to handle the SelectedIndexChange event of the dropdown control.
Regarding your 2nd question:
I suggest you remove the AutoPostBack from the dropdown, add an "Update" button, and update the data in the button Click event.
The button can hold Command and CommandArgument values, so it's easy to associate with a database record.
some MSDN links with C# examples on bubbling
http://msdn.microsoft.com/en-us/library/system.web.ui.control.onbubbleevent.aspx
http://msdn.microsoft.com/en-us/library/aa719644(VS.71).aspx
http://msdn.microsoft.com/en-us/library/aa720044(VS.71).aspx
Thank You for your solution
protected void ddlOnSelectedIndexChanged(object sender, EventArgs e) {
try {
ModalPopupExtender1.Show();
if (ViewState["Colors"] != null) {
FillColors(ViewState["Colors"].ToString());
}
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
Image image = (Image)dataListItem.FindControl("mdlImage");
Label ProductCode = (Label)dataListItem.FindControl("lblprdCode");
Label ProductName = (Label)dataListItem.FindControl("lblProdName");
DropDownList ddlQuantity = (DropDownList)dataListItem.FindControl("ddlQuantity");
Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
Label TotalPrice = (Label)dataListItem.FindControl("lblTotPrice");
//Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
} catch (Exception ex) {
}
}

Categories