ASP.NET C# Set OnSelectedIndexChanged from Code Behind - c#

Im trying to set the SelectedIndexChanged from the code behind of a Web Forms application. I have a variable amount of dropdowns being added onto the page from the database and need a method to trigger each time one of the dropdowns change.
Im currently trying:
ddlProductCause.SelectedIndexChanged += new EventHandler(ddlProductCause_Changed);
ddlProductCause.ID = "ddlProductCause_" + row["item_id"].ToString();
ddlProductCause.AutoPostBack = true;
and...
public void ddlProductCause_Changed(object sender, CommandEventArgs e)
{
// do stuff
}
But I have no luck.
Any ideas?

Event Argument may cause this, use EventArgs
protected void ddlProductCause_Changed(object sender, EventArgs e){
//to get id
DropDownList ddl=sender as DropDownList;
//ddl.Id <---Access property like this.
}

Related

ViewState value not being retained during postback

How can I make this piece of code work? I am dealing with a bigger issue but if I can make this work then I will know what to do.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Response.Write(ViewState["Value"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Value"] = "Button clicked";
}
Page_Load event happens before Button1_Click and hence you wont be able to access a value that is not already set.
You will need to use an event that happens after Button1_Click like Page_PreRender as you have used in the answer.
Please go through this link to understand Page Life Cycle, which is invaluable in Asp.Net Webforms development.
I was able to solve my problem by putting my logic in pageLoad method in the page_PreRender method like this:
protected void Page_PreRender(object sender,EventArgs e)
{
if (IsPostBack)
{
Response.Write(ViewState["Value"].ToString());
}
}

C# combobox dropdown

I Want my combobox to drop down when i press the textfield and the dropdown symbol
I have done this:
private void comboBoxOpretKomponentLevel_Enter(object sender, EventArgs e)
{
if (comboBoxOpretKomponentLevel.SelectedIndex <= 0)
{
comboBoxOpretKomponentLevel.Text = null;
}
comboBoxOpretKomponentLevel.Focus();
comboBoxOpretKomponentLevel.DroppedDown = true;
}
The .Droppeddown = true makes it work if text is selected ("Select Product")
But when the dropdown symbol of dropbox is pressed - the droppeddown goes false again.
How do I make this work?
And as far as I know I cant use DropDownList because i canĀ“t have my ("Select Product") Text.
I would simply use the MouseClickevent. Since you're question is too broad I only have this piece of code that may help you.
What it does is that only if you click the ComboBox or any controller regarding that ComboBox it is going to open the dropdownlist. To close it simply click on the Form_Load event and it will idle the dropdownlist
private void comboBoxOpretKomponentLevel_MouseClick(object sender, MouseEventArgs e)
{
//This piece will dropdown the combobox once you click it.
comboBoxOpretKomponentLevel.DroppedDown = true;
comboBoxOpretKomponentLevel.Focus();
}
private void YourForm_Click (object sender, EventArgs e)
{
//This piece will simply close the dropdown from your combobox and use the selected value.
comboBoxOpretKomponentLevel.DroppedDown = false;
}
Hope it helps, otherwise simple reformulate your question so we can help you.

Why does my variable lose its value?

From the selectedindexchanged event, my variable has a value, but when it reaches the btn_click() event, the variable no longer has a value. Why is that?
public partial class TestingDatapass
{
private string item = null;
private string itemprice = null;
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
//Both have a value here
item = item.SelectedValue;
itemprice = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
//no value here
totalprice = Convert.ToInt32(itemprice)*Convert.ToInt32(item);
MessageBox.Show(totalprice);
}
}
EDIT
And to answer the ? posed in comments, the order of occurrence is the selectedindexchange THEN the btn_click()
EDIT REGARDING View State
So then would this be a proper way to set up what I am trying to achieve?
public partial class TestingDatapass
{
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
ViewState["item"] = item.SelectedValue;
ViewState["itemprice"] = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(ViewState["item"])*Convert.ToInt32(ViewState["itemprice"]);
}
}
When a page is requested, ASP.NET creates an instance of TestingDatapass class and initialize itemprice,totalprice etc. fields. Now when you change your dropdown from client (which I assume looking at your item_selectedindexchanged method), Postback happens and it assign values you have mentioned in item_selectedindexchanged. Finally it destroys the instance, generates the html and sends it back to browser.
Now, when you press the button in your page then a new instance is created, your fields are re-initialized and you don't see the changed values in btn_click. This is how it works.
Thus if you want to preserve any data across postback, Consider using any State Management technique like ViewState, HiddenField etc.
Also, as a side note, MessageBox.Show is not available in ASP.NET.
Update:
I answered in the context of why it is not retaining the value in button click event, there are many ways to do it. But to answer your question, I don't see any reason to store the values in item_selectedindexchanged event as you are not doing anything there. You can directly access the dropdown selected values in button click handler like this:-
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(item.SelectedValue) *
Convert.ToInt32(item.SelectedItem.Text);
}
Also, please note it's item.SelectedItem.Text and not SelectedValue.Text.

Session variable + WebMethod variable value not updating

I have a web app with a dropdown list. When a new index is selected I have to storing the value to a session variable, which is created on Session_Start event.
protected void Session_Start(object sender, EventArgs e)
{
Session.Add("testValue", "test");
}
On selectedindex changed event i'm setting the new value like this
Session["testValue"] = DropDownList.SelectedItem.Text;
I have a web service where I retrieve the value of the session variable like this:
[WebMethod(EnableSession = true)]
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
From a console app I connect to the web service and retrieve the value returned by getValue(), however the initial value is always being returned. any idea please?
The issue is because when the console app is run it seems that a new session is created. Using Application state using Application.Set and Application.Get solved the issue. Hopefully i will not have issues when the system will be used by multiple users.
Check whether the values of the items in your dropdown list are different.This is essential for your selected index changed event to be fired.
Here the values are not changed, You didn't change the values. So nothing expected
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
The mistake is probably in dropdownlist
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["testValue] = dropdownlist1.SelectedItem.text;
}
}
And,
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["testvalue"] = dropdownlist1.SelectedItem.text;
}
Also try with
System.Web.HttpContext.Current.Session["testvalue"]
in both parts

In ASP.Net C#, on button click event I find the FileUpload Control within DataList and It gives error?

This is the Error:
Collection was modified; enumeration operation may not execute.
This error is found when for each process tries to find the items.
protected void SubmitButton_Click(object sender, EventArgs e)
{
foreach (DataListItem item in this.ImageRepeater.Items)
{
FileUpload fup = (FileUpload)ImageRepeater.FindControl("ImageUpload");
if (fup.HasFile)
{
updateImageChanges();
divTopImageCheckChangedmessage.Visible = false;
}
}
}
My requirement is that I want to satisfy the check if there is no file loaded into Fileupload control within ASP.Net DataList then not to allow, the updateImageChanges(); function to be hit.
I will be grateful to you all.
Not sure why you are looping through the DataList Items ,I think your code may look something like this :
Check this sample code for
protected void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
DataListItem di = btn.NamingContainer as DataListItem;
FileUpload fu = di.FindControl("fu") as FileUpload;
if (fu.HasFile)
{
// save to the database :
}
}
I think this error is your updateImageData call method gave
Since updateImageChanges() doesn't take a parameter, I assume it iterates through your repeater items again? How does it know what item to work with? Whatever your are doing in that function (since you did not post the code for it) is the source of your error, it is not in the code you posted. However, this solution will work for you:
You can update that function to take a parameter (say a FileUpload control) and then pass that from your if statement to the updateImageChanges() method. That way this method will ONLY update changes, and not need to loop through your repeater items again to get what it needs.
Something like this:
protected void SubmitButton_Click(object sender, EventArgs e)
{
foreach (DataListItem item in this.ImageRepeater.Items)
{
FileUpload fup = (FileUpload)ImageRepeater.FindControl("ImageUpload");
if (fup.HasFile)
{
updateImageChanges(fup);
divTopImageCheckChangedmessage.Visible = false;
}
}
}
private void updateImageChanges(FileUpload fup)
{
// remove your code that loops through to get to the correct file upload
// leave code that works with current fup and use passed parameter instead of the repeater items collection
}

Categories