how to show search data after postback function call in asp.net - asp.net

gridview details show exactly what as i want even search data also show fine but problem is when i post back page and return on search page search is not maintain in gridview i use gridview.Databind() function on page load use (!page.postback) function but then also not useful for me so please can you all give me any code for that
on page load i write but not useful for me
if(!page.postback)
{
sda = new SqlDataAdapter("Select Name,ContactNo,Address from gridviewtable",con);
ds = new DataSet();
sda.Fill(ds);
gvd_detail.DataSource = ds;
gvd_detail.DataBind();
}

Here are some solution :
1- After every user search , Redirect user to page with parameter( like query string) and then on that page retrieve parameter and show appropriate result
2-Asp.net pages by default maintain page state by "View-state" , First make sure ViewState property of the page is True , Then make sure in page life cycle where you have rebind gridview
3-If there is situation in which #2 solution didn't work , There are another solution and that is saving page state in ViewState page explicitly
Hope these help

Related

ASP.NET Database searching using dropdown list with paging

I created ASP.NET MVC Web App. I've got a question about searching in database using dropdown list with paging. I used this tutorial:
tutorial, so my code is the same.
And I also created dropdown list in View:
Search: #Html.DropDownList("type", ViewBag.currentType as string)
I tried to do it the same way as it was done in tutorial, but searching works fine only until I go to the second page. When page is changed, searching is reset to default, first type.
Creating my list:
var typeList = new List<string>();
var type = from o in db.Typies
orderby o.Name
select o.Name;
typeList.Add("all");
typeList.AddRange(type.Distinct());
ViewBag.type = new SelectList(typeList);
I can easily get selected item, but have no idea how to make it selected after page is changed. So, my question: How can I restore/set selected dropdownlist item when page is changed?
Problem solved. I figured out I can manage selected dropdownlist value between pages by saving it as a Session parameter and check that parameter on every page :)

Textbox not updating on page load ASP.net

I have a dynamically built table on the page load of my web page containing textboxes with defaults that can be changed by the user. There is also some validation on the user input values (e.g., input can not be less than zero). When the user submits the table, only valid inputs are stored, and the page is refreshed pulling the stored values to populate the table when it is rebuilt. For some reason the textboxes will still display invalid inputs after submitting and reloading the page even though they are not persistent, and this problem does not happen for labels.
Is there something specifically built into the textbox control causing this issue? Is there somewhere storing the state, perhaps (I tried setting the ViewState flag to false)? Is this just some part of the page lifecycle?
The textbox is built in a method called from the Page_Load event
void Page_Load(object sender, EventArgs e)
{
//page initialization...
ValidateData(); //This is where the current data is verified, and stored if valid
BuildTable(); //This takes that stored value for the text
}
void BuildTable
{
tbTable = new Table();
tbRow = new TableRow();
tbCell = new TableCell();
TextBox tb = new TextBox();
tb.text = some stored value;
tbCell.Controls.Add(tb);
tbRow.Cells.Add(tbCell);
tbTable.Rows.Add(tbRow);
divFromPage.Controls.add(tbTable);
}
If more information is necessary to help with this issue, just let me know.
Edit :
After reproducing your problem i came to the following conclusion.
I believe the problem is not the viewstate but asp is just repopulating these values because the form data which you submited has the same name as the input element which you are returning.
Even though you generate them dynamicly since you add them to the same div the result is always the same. This leads me to 2 solutions :) :
My solution nr 3 still stands , i tried it out and on button click redirecting works as intended with no posted data creeping back into my textbox.
This statement takes care of that :
Response.Redirect("~/test.aspx");
Alternativly you could generate a random ID to make sure the inputfields names you are returning are different from the ones that were submited. You wouldn't have to change all the names but if the table ID for example is different the entire table won't get populated with the submitted data anymore.
Be aware that you might need a if(IsPostBack) in your pageload because your data will be lost right after pageload(unless you handle the saving before that)
If you are doing a postback asp.net uses it's viewstate to maintain all the textbox,textfields and all other form elements(including input type hidden).
I currently see 3 solutions to your problem :
You could do what ivowiblo suggested, before you load the data from the database( i assume you do) you could wipe all the textfields. On a first time visit this will be pointless off course since they are blank. But after a postback it will actually wipe the textfields.
You could disable the viewstate on those textboxes so asp will not persist the state. I'm not sure why your test didn't work but it should work. If you choose this approach feel free to edit your question with some actual code
My personal favorite : Redirect the page. In stead of just returning the result and causing a postback to the page do the following : after the user hits the save button you can save the data and then do a Response.Redirect to your current page. The browser will be redirected to the page and no viewstate will be involved.
Just figured this out, kind of a D'oh moment, I just populated the data in the PreRender event and it works just fine, thanks for all the input.

JQuery and ASP.NET Web Forms

I am creating a ASP.NET Web Form application where I am trying to use some nice jQuery functionality and flashyness. The current part of the application I have consists of two jQuery UI tabs; a search tab and a results tab. When the user performs a search from the search page, the results tab will be selected and the results will be displayed in this tab. I need to get the results into a gridview. Now this is where the issue starts to come in:
The easiest way to get the search results is to allow the search click to perform the postback where I can then format the datasource with the parameters from the input fields and let the datagrid take care of itself and data bind and show the results. The thing is, this really doesn't look that great (due to the whole post back and such) as well as starts to cause some issues with using javascript/jQuery to take care of tab switching and all that portion because the postback reinitializes everything from the jQuery UI (i.e. the jQuery UI tabs). So in short, the postback allows for easy binding of the input for the search and getting the results, but makes the page and its behavior all wonky.
I was wondering if there is a standard way to do this type of mixing jQuery/javascript/AJAX all together within web formto get the functionality of things like the gridview and such. I am wondering if there are some good tutorials, or even just a direction on solving this issue.
I hope all this made sense, and thank you all for your help.
I don't think this is a standard, but here is the pattern I use:
First of all, I use Page Methods for ASP.Net to get hooked back up to the server. In this case it would be something like this:
PageMethods.Search(searchValue, onSearchComplete);
That calls a static page method in the page, like this:
public static void Search(string searchValue)
...
Inside that procedure, I create an instance of a user control which contains the gridview, and invoke a method on that control, passing the searchValue:
var searchControl = (SearchControl)new SearchControl().LoadControl("/controls/SearchControl.ascx");
searchControl.Search();
var stringBuilder = new StringBuilder();
using (var textWriter = new StringWriter(stringBuilder))
{
var htmlWriter = new HtmlTextWriter(textWriter);
searchControl.RenderControl(htmlWriter);
return stringBuilder.ToString();
}
This is all going to end up as the result argument to the handler you specified in the initial call (onSearchComplete) in this example. You can do whatever you want with the markup, including slapping it into a div, or alerting it for debugging.

CrossPost access to data

I have a search form on a page that posts back to itself and shows the results, all works fine. I now have a requirement to put the same search form on the site home page. This needs to post back to the search form and run the findResults code. Using the PostBackURL parameter on the home page form's submit button I can hit the search page ok. However, when using the following code in the Page_Load section of the search page I hit the problem of not being able to access data from the posting page as I get the following error message on the line starting "yearList.SelectedValue....": "'Site._default1.Protected WithEvents yearList As System.Web.UI.WebControls.DropDownList' is not accessible in this context because it is 'Protected'".
'#################################
'# Handle form post from Home page
'#################################
Dim crossPostBackPage As Site._default1
If Not (Page.PreviousPage Is Nothing) Then
If Not (Page.IsCrossPagePostBack) Then
If (Page.PreviousPage.IsValid) Then
crossPostBackPage = CType(PreviousPage, Site._default1)
yearList.SelectedValue = crossPostBackPage.yearList.SelectedValue
getAvailability()
End If
End If
End If
As I didn't declare yearList Protected, I don't know where to change it or how to.
Any advice would be appreciated,
Craig
dim prevYearList as ListBox = CType(PreviousPage.FindControl("yearList"),ListBox)
reference: http://msdn.microsoft.com/en-us/library/ms178139.aspx
note: the vb is a quick off the top of my head translation of my tested c# code, so don't take it literally.

Postback with Modified Query String from Dropdown in ASP.NET

My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns).
They can select a report using two methods. With SelectedReport=MyReport in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down.
My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want SelectedReport=MyNewReport in the query string and the page to post back.
At the moment it's just doing a normal postback, which leaves the SelectedReport=MyReport in the query string, even if it's not the currently selected report.
Edit: And I also need to preserve ViewState.
I've tried doing Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true) in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown.
Maybe I'm asking the impossible or going about it completely the wrong way.
#Craig The QueryString collection is read-only and cannot be modified.
#Jason That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).
You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page.
EDIT: Here is some quick and dirty code that is indicative of what would do the trick:
<script>
function changeReport(dropDownList) {
var selectedReport = dropDownList.options[dropDownList.selectedIndex];
window.location = ("scratch.htm?SelectedReport=" + selectedReport.value);
}
</script>
<select id="SelectedReport" onchange="changeReport(this)">
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>
Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example).
#Ray: You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?
If it's an automatic post when the data changes then you should be able to redirect to the new query string with a server side handler of the dropdown's 'onchange' event. If it's a button, handle server side in the click event. I'd post a sample of what I'm talking about but I'm on the way out to pick up the kids.
Have you tried to modify the Request.QueryString[] on the SelectedIndexChanged for the DropDown? That should do the trick.
You could populate your dropdown based on the querystring on non-postbacks, then always use the value from the dropdown. That way the user's first visit to the page will be based on the querystring and subsequent changes they make to the dropdown will change the selected report.
The view state only lasts for multiple requests for the same page. Changing the query string in the URL is requesting a new page, thus clearing the view state.
Is it possible to remove the reliance on the view state by adding more query string parameters? You can then build a new URL and Response.Redirect to it.
Another option is to use the Action property on the form to clear the query string so at least the query string does not contradict what's displayed on the page after the user selects a different report.
Form.Action = Request.Path;
You can use the following function to modify the querystring on postback in asp.net using the Webresource.axd script as below.
var url = updateQueryStringParameter(window.location.href,
'Search',
document.getElementById('txtSearch').value);
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("searchbutton", "",
true, "aa", url, false, true));

Resources