Dynamic data load on ASPX page - c#

I have an internal web service (ASP.NET) written on C# in a company I work for. There are only 2 pages in it, one of this pages contains DropDownList.
Every time when user selecting an item from that DropDownList I need to somehow pass selected item value to a static method and show result string of that method anywhere on page.
I've never worked with ASP.NET or any web programming before and a bit confused about how to do it, not sure where to start looking even.

In your aspx file you should have this:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
onselectedindexchanged="ListBox1_SelectedIndexChanged"></asp:ListBox>
Notice the AutoPostBack="True" which goes back to the server and fires the selectedindexchanged event immediately after the user changes the selection in the listbox
In your code-behind (.cs file)
You should have this:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Call static method and pass the ListBox1.SelectedIndex
// MyStaticMethod(ListBox1.SelectedIndex);
}

you can either se5t the autoPostBack="true" and handle the change event on the server side or using jQuery subscribe for the change event and get the value on the client side

You should probably check out some of the great resources that microsoft provides for new .NET developers. They will be really helpful in getting you started. Her is a link of some really good videos to help you out: http://www.asp.net/web-forms/videos
Not sure what language you are coming from, if any... But for the most part webforms is going to work a lot like other web based methodologies.
Your ASP.NET Controls (in your case the DropDownList) have both client and server side events.
You will probably want to map the server-side OnSelectedIndexChanged event on your DropDownList.
In order to cause a postback on that control you will want to set the AutoPostBack property to true on your DropDownList.

try this one
In html ,
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
In aspx.cs page,,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selctedValue = DropDownList1.SelectedValue;
/// Call yours static methid here
YourMethod(selctedValue);
}

Related

SelectedValue & SelectedItem From Drop Down List

I am attempting to write the selected values to two separate text boxes named this.txtTextSelected.Text = text; and this.txtValueSelected.Text = value;
My issue is that the values are not written to the two text boxes, and when an option is selected my page refreshes and doesn't actually store the selected value which makes me think
1) Either my HTML for the drop down list is incorrect
2) I have added un-needed syntax for something
But I am scratching my head as to what the real deal is.
This is my HTML for the drop down list
<asp:DropDownList ID="dropdownlist1" CssClass="DropDownLists"
runat="server" Width="90px"
AutoPostBack="true"
OnSelectedIndexChanged="dropdownlist1_SelectedIndexChanged">
</asp:DropDownList>
And this is my C# code behind for the page
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = dropdownlist1.SelectedValue;
string text = dropdownlist1.SelectedItem.Text;
this.txtValueSelected.Text = value;
this.txtTextSelected.Text = text;
}
EDIT
Will this remedy my problem (basing this off #David comment below)
if (!IsPostBack)
{
BindDropDownList();
}
(In response to comments and the question edit...)
Unlike WinForms, WebForms "form" objects don't persist in memory. Web applications are designed to be inherently stateless. So every request results in re-instantiating the targeted form object, which invokes all of the start-up stuff that happens in a form.
This includes Page_Load.
So any time you click a button or do anything that involves posting the page back to the server, Page_Load (and other initialization events) happen again, before any event handlers or custom logic.
This means that if you're binding your controls in Page_Load, you're going to re-bind them before you try to use them. In WebForms, the standard fix for this is to wrap them in a conditional when binding:
if (!IsPostBack)
{
// bind your controls
}
This will bind the controls when initially loading a page, but not when re-submitting the page's form to the page (posting back).

Why is ASP.NET submitting the original value of a TextBox control when the contents have been changed?

I have a web form that allows the user to modify data in certain fields (mostly TextBox controls, with a couple of CheckBox, DropDownList, and one RadioButtonList control) with a submit button to save the changes. Pretty standard stuff. The catch is, I need to keep track of which fields they modified. So I'm using ASP.NET HiddenField controls to store the original value and then on submit comparing that to the value of the corresponding TextBox (for example) control to determine which fields have been modified.
However, when I submit the form and do the comparison, the value of the TextBox control in the code behind still reflects the original value, even though I have changed the contents of the TextBox, so it isn't registering the change. Here is an example of a set of TextBox/HiddenField pairings (in this case last, first, middle names) in my ASP.NET form:
<div id="editName" class="editField" style="display: none">
<asp:TextBox ID="tbxLName" runat="server" class="editable"></asp:TextBox>,
<asp:TextBox ID="tbxFName" runat="server" class="editable"></asp:TextBox>
<asp:TextBox ID="tbxMName" runat="server" class="editable"></asp:TextBox>
<asp:HiddenField ID="hdnLName" runat="server" />
<asp:HiddenField ID="hdnFName" runat="server" />
<asp:HiddenField ID="hdnMName" runat="server" />
</div>
I'm setting the original values of all these controls (".Text" for the TextBox controls, ".Value" for the HiddenField controls) on PageLoad in the code behind.
Here's an example of where I'm doing the comparison when I submit the form (I'm adding the field name, old value, and new value to List<string> objects if the values differ):
if (tbxLName.Text != hdnLName.Value)
{
changes.Add("ConsumerLastName");
oldVal.Add(hdnLName.Value);
newVal.Add(tbxLName.Text);
}
But when I enter a new value into the TextBox control and click Submit:
then step through the code in the debugger, it shows me that the value of the control is still the old value:
Why is the comparison happening against the original value of the TextBox even though the new value is there when I click the submit button?
Update: #David gets the credit for this, even though he didn't post it as an answer -- I was forgetting to enclose the method for pre-filling the original values of the controls in a check for IsPostBack; I really should have known better, I've been doing this for quite a while!
Are you checking for IsPostback in Page_Load so you don't overwrite the values sent in the Postback?
Make sure that you are not overwriting your values in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
someTextField = "Some Value";
}
}
It took a while for me to get that the Page_Load method works as an "before anything goes" method and not only a method that is being ran when you visit the page with GET.
Make sure you're not overwriting the value for the textbox somewhere in page init or load without checking for the IsPostback flag.
It may happen due to postback. If you code for set textbox not in !isPostBack then put it.
i.e.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tbxLName.Text="anything";
}
}

PostBackTrigger for FileUpload functionality inside a GridView

I have an asp:GridView control inside a .aspx page that the user can add several rows of data to. The user must also be able to attach a file to each row of data added.
For this I use the following inside the GridView:
<asp:TemplateField HeaderText="Upload" HeaderStyle-Width="120px">
<EditItemTemplate>
<asp:FileUpload ID="fuUploadLocation" runat="server" Width="98%" TabIndex="18" />
</EditItemTemplate>
</asp:TemplateField>
Then to save the location of the file upload I use the RowUpdating event in code-behind to set the value etc.
The problem is I can't register a PostBackTrigger for the control on the html as it doesn't pick it up as it's inside the GridView. I've tried setting it dynamically from other examples but can't seem to get this to work, the result being my FileUpload's FileName is always empty and the file then doesn't save correctly.
Any suggestions would be awesome.
Thanks
On Gridview row databound you have to find the file upload control and then add it to your UpdatePanel postback trigger.
I've not found a solution to my problem but I did work around it (sort of). I know just add a link to the grid, when user clicks it sends ID through via querystring, a new page opens that handles the entire upload process and returns the url of the saved document.
Not ideal but it works and saved me hours of frustration.
In the OnItemDataBound event handler of the grid need to call ScriptManager.GetCurrent(this).RegisterPostBackControl(ControlID);
This is an old post but for anyone that is stuck with it, you need to add the following to your control as stated in the other answers.
protected void ItemDataBound(object sender, EventArgs e)
{
Button myButton = (Button)e.Item.FindControl("myButton");
if (myButton != null)
ScriptManager.GetCurrent(Page).RegisterPostBackControl(myButton);
}
You also need to change the enctype in your form tag to the following e.g.:
protected void Page_PreRender(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
It should then work without an issue.

What is the effect of IsPostBack Condition?

I have a aspx Page where I am using AJAX. like
<asp:UpdatePanel runat="server" ID="upPanelDDLProgram">
<ContentTemplate>
<asp:DropDownList ID="DDLProgram" runat="server" Width="194px" Height="18px" OnSelectedIndexChanged="OnDDLProgramChanged" AutoPostBack="true">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
and my code behind is like
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
//{
// BindProgramDDL();
//}
BindProgramDDL();
}
protected void BindProgramDDL()
{
List<CcProgramEntity> programEntities = FormSaleSubmit_BAO.GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = FormSaleSubmit_BAO.GetAllPrograms();
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
the If condition is the page load event, is commented out. If I toggle the comment part of the page load event, it works perfect in both cases. My question is why is this heppening?
IsPostBack tells you if it is a second request to the page. The benefit here is if you need to do anything costly, such as a database call to fill a dropdownlist or similar, you can do it when !IsPostback, then use ViewState to retain the values.
To put it specific to your situation
Using:
if (!IsPostBack)
{
BindProgramDDL();
}
Will result in BindProgramDDL being called ONLY on the first time the page is loaded, all AJAX or other user interaction with the page will NOT call BindProgramDDL;
Without that, in place EVERY page load would call the method, un-necessarily hitting the database for the records.
If I am getting you correct .......
DropDown list has data even you are not binding it second time after post back..........its becasuse its server side control and each serverside control has its view state with it thats y its not removing data.
IsPostBack - it true when do the post back by using serverside control like dropdown, checkbox , textbox............When you load page first time this property is false but in subsequent request to same page value of this property is true. you can check msdn document for more detail about it.
It's basically saying are you visiting the page for the first time (not a post back), or has the user clicked on a control (a post back).
Useful for when you only want to run methods once when the page is initially loaded
You're code should probably look like this to achieve best results
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindProgramDDL();
}
}
I suspect that the DropDownList saves the items in the ViewState and then work with them during all subsequesnt requests. That is why your code works even if the editor's DataSource is set only when IsPostBack returns false.
PostBack event appears on every action (ajax too), except of first page load.
Page.IsPostBack
indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
see http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
Since you've bound your datasource the first time the page was loaded, the data are still in the viewstate and you don't need to update the control (unless the datasource has changed).
Take also into account that, since you're using ajax, you may also want to intercept if there was an 'asynchronous postback'.
See http://encosia.com/are-you-making-these-3-common-aspnet-ajax-mistakes/

UpdatePanel reloads the whole page

I'm building an asp.net cutom control inside which I have two dropdownlists: companyIdSelection and productFamilySelection.I populate the companyIdSelection at Page_Load and in order to populate the productFamilySelection depending on the selected item in companyIdSelection.I'm using UpdatePanels to achieve this, but for some reason every time I update companyIdSelection Page_Load is being called ( which as far as I know should happen only when the entire page is reloaded ), the list is being reloaded again and the item the user selected is lost( the selected item is always the top one ).Here's the code
<asp:UpdatePanel ID="updateFamilies"
runat="server"
UpdateMode="Always">
<ContentTemplate>
Company ID:<br>
<br></br>
<asp:DropDownList ID="companyIdSelection"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="companyIdSelection_SelectedIndexChanged">
</asp:DropDownList>
<br></br>
Product Family:
<br></br>
<asp:DropDownList ID="productFamilySelection" runat="server"
AutoPostBack="True"
onselectedindexchanged="productFamilySelection_SelectedIndexChanged">
</asp:DropDownList>
<br>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
this.companyIdSelection.DataSource = companyIds(); //companyIds returns the object containing the initial data items
this.companyIdSelection.DataBind();
}
protected void companyIdSelection_SelectedIndexChanged(object sender, EventArgs e)
{
// Page_Load is called again for some reason before this method is called, so it
// resets the companyIdSelection
EngDbService s = new EngDbService();
productFamilySelection.DataSource = s.getProductFamilies(companyIdSelection.Text);
productFamilySelection.DataBind();
}
Also, I tried setting the UpdateMode of the UpdatePanel to "Conditional" and adding an asyncpostback trigger
but the result was the same.
What am I doing wrong?
PS:
I fixed the updating problem, by using Page.IsPostBack in the Page_Load method, but I would still want to avoid a full postback if possible
I think you misunderstand how UpdatePanels work. They DO actually do a full page postback, it's just that during the rendering stage they capture only a portion of the output and send it back in the AJAX response so the page can be updated. More info here.
So you will still need to check whether it is a postback in your page_load event and only perform your data load if it isn't one.
The update panel call back will go through the page load on every call back. In face, the pull page lifecycle (minus render and prerender) will occur. Update panels give the appearance of ajax, but your client side code still posts back to the same page - which is the problem you are describing. If you can avoid using Update Panels, I suggest you do so. Use something like jQuery instead. If not, then use this in your Page_Load
if (Page.IsCallback) { } //Do callback specific code here
else { } //Do Postback specific code here
Hope this helps. Good Luck.

Categories