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

(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) {
}
}

Related

C# WinForms ListBox changes selection to first item

I got a problem with a ListBox in a WinForm application. I have two ListBoxes inside of a tab control and depending on the selection in the first one (lb1), the DataSource of the second one (lb2) changes. This is done in the SelectedValueChanged Event.
private void listBox_ControlUnits_SelectedValueChanged(object sender, EventArgs e)
{
ControlUnit unit = (sender as ListBox).SelectedItem as ControlUnit;
textBox_ProjectNameTab.Text = unit.ProjectName;
listBox_ControlCircuits.DataSource = null;
listBox_ControlCircuits.DataSource = unit.ControlCircuits;
}
lb1 is filled with a DataSource, too.
Now if I select a value in lb1 the selection automatically jumps back to the first item and I can not figure out why. is this some kind of UI update problem?
Even without the SelectedValueChanged event and the connection to the second listbox the issue occures.
Short gif of the problem, sorry for the blurriness
If I select one item more than once it works somehow (as seen in the gif).
Edit:
I found the problem but I do not quite understand what happens.
I have another listBox on another tab of my tab control. This listBox has the same DataSource as lb1. This seems to cause this behavior.
I finally found the problem:
I did not know that if I use the same DataSource for two ListBoxes they share the BindingContext per default.
I created a new BindingContext for the second ListBox and now the selection does no longer change.
listBox_allGroups.DataSource = null;
listBox_allGroups.DataSource = x.y;
listBox_allGroups.DisplayMember = "Name";
listBox_ControlUnits.DataSource = null;
listBox_ControlUnits.DataSource = x.y;
listBox_ControlUnits.DisplayMember = "Name";
listBox_ControlUnits.BindingContext = new BindingContext();
You can use a variable to hold the selected item
object _selecteditem=null;
and check it in ListBox click event.
prive void ListBox1_Click(object sender,EventArgs e)
{
if(ListBox1.SelectItem == _selecteditem) return;
// do ...
}

How can i change value from textbox in row in gridview?

I am getting value from textbox in gridview and trying to change the value with two different buttons. (increase and decrease buttons) First click is working than not working.
I was checking browser's console for getting information and i am getting this information: "XHR finished loading: POST" Do you have an idea why button click works only once?
Here is my code for increase:
public void btn_increase_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gridview1.Rows)
{
Textbox quantity = (Textbox)row.FindControl("txt_quantity");
int input_quantity = Convert.ToInt32(quantity.Text);
if(input_quantitiy >= 0)
{
quantity.Text = Convert.ToString(input_quantity + 1);
}
}
}
UPDATED
If you have copied that code exactly from your program there are a few issues you could try fixing that might help:
input_quantity in the if() statement is spelt incorrectly.
Swap the = and > around in the if statement, currently isn't checking for greater than or equal too, but is a lambda expression.
Also if you know the ID of the TextBox, and only need to increase/decrease one TextBox, is there any reason to iterate through the GridView? You could achieve the same thing as follow:
TextBox quantity = txt_quantity;
int input_quantity = Convert.ToInt32(quantity.Text);
if (input_quantity >= 0)
{
quantity.Text = Convert.ToString(input_quantity + 1);
}
I found a solution and it's very simple. If your button click is not working and getting "XHR finished loading: POST" error on browser. Check your Page_Load and be sure bind gridview in if page is not postback like that:
if(!IsPostBack)
{
gridview.DataSource = dataset.Tables[0];
gridview.DataBind();
}

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.";
}
}

asp.net drop down list duplicated itself when post back

It is a very weird problem
when I change the value of the drop down list, a new drop down list is show. I am so confused,
To know what I am talking about, please check these images.
edit
code for bind
CallerId = Request["CallerID"];
if (String.IsNullOrWhiteSpace(CallerId)) return;
var results = ZumaDa.GetCustomerInformation(CallerId);
rowCount = results.Rows.Count;
CallerId = rowCount > 0 ? results.Rows[0][4].ToString() : CallerId;
if (rowCount > 1)
{
ListView1.Enabled = false;
GridView1.DataSource = results;
GridView1.DataBind();
}
else
{
GridView1.Enabled = false;
ListView1.DataSource = results;
ListView1.DataBind();
}
That code is in page load and NOT on !ispostback
Since you updated your question with the ListView markup, and your Page_Load code, it appears the problem of the duplicated DropDownList goes away after you wrap your databinding code in an if (!Page.IsPostBack) block.
One problem in your code is that, in your SelectedIndexChanged event, you're searching the ListView for your DropDownList and TextBox. You need to search the ListViewItem control where the SelectedIndexChanged event occurred.
To do that, you can first get the DropDownList from the "sender" parameter. Then you should find the "NamingContainer" control of the DropDownList, and search that. Like this:
var dropDown = (DropDownList)sender;
var visitID = (TextBox)dropDown.NamingContainer.FindControl("visitID");
That second line of code might need to have an additional ".NamingContainer" depending on your markup.
I think you need to bind listview in !IsPostback check means when do postback it pageload event fired and it bind dropdown with second time or if its not please share binding code

Dropdownlist in masterpage value not updated after new selected

I would like some help with the following problem. I have a dropdownlist implemented in my masterpage. It has an sql data source from which it loads the values of companies. Depending on which value(company) selected, it shows that value in a label on a different page.
The ddl which is in the masterpage is ofc still visible and should display the selected value which it does at the 1st time a value is selected. But when i select another value in the ddl it shows the value which was 1st selected and so on. So it doesn't update or something.
My code:
This is the onselectedIndexChanged event handler:
protected void DropDownListType_SelectedIndexChanged(object sender, EventArgs e)
{
String input1 = DropDownListType.Text;
String input2 = DropDownListType.SelectedValue;
String url = "~/test.aspx?pcompany="+input1;
DropDownListType.SelectedValue = input2;
Session["Company"] = input2;
Response.Redirect(url);
}
and this is the code i'm using in my Page_load method from the masterpage:
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
If I remove this last piece of code from my page_load method it updates the label with value on the redirected page but it resets my ddl to default value instead of keeping it at 4 when value 4 selected.
I hope this is a bit clear to you all. Any help is appreciated. Ty in advance.
try setting the label value in the PreRender() method. The problem you're having is with the page life cycle. I would change your OnLoad method to use
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}
This way you're only setting it once when the page loads and from then on the page will set the selected value automatically using viewstate.
The Load event is fired before the SelectedIndexChanged event, that's why you don't have it set in Session yet.
See ASP.NET Page Life Cycle
just set the AutoPostback property of the DropDownList to true and then it will work.
This is because otherwise the onselectedIndexChanged will be called only on PostBack from a button or any other field.
And also, as the above answer says, use this code:
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}

Categories