Paging Problems With Standard .net 2.0 Gridview using VB.Net - asp.net

I am using a standart .net 2.0 Gridview which uses an XMLDatasource to populate the Grid. The Data property of the XMLDatasource is set dynamically which allows the gridview to change based on input.
All this works fine however I am having problems with paging...
I have set the AllowPaging Property to "true" and set the PageSize Property to "10". The GridView populates fine the first time around showing the first 10 records and the number of pages as hyperlinks at the bottom, BUT when i try to click on any of the page numbers to view them a message box pops up saying "Object reference not set to an instance of an object"
any ideas what I'm doing wrong?? or is there anything i need to do which i have missed out on??
Code currently being used;
Gridview...
<asp:GridView ID="GridView1"
Runat="server"
DataSourceID="XmlDataSource1"
AutoGenerateColumns="False"
AllowPaging="True"
style="width:100%; height:100%;"
EnableViewState="False">
<SelectedRowStyle BackColor="Red" />
<Columns>
<asp:BoundField DataField="TYPE" HeaderText="TYPE" SortExpression="TYPE" />
<asp:BoundField DataField="DESCRIPTION" HeaderText="DESCRIPTION" SortExpression="DESCRIPTION" />
</Columns>
</asp:GridView>
XMLDatasource...
<asp:XmlDataSource ID="XmlDataSource1" runat="server" TransformFile="~/XML/grid2.xslt" EnableCaching="False">
</asp:XmlDataSource>
vb.net code which sets the Data property of the XMLDatasource...
Private Sub btnTest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTest.Click
XmlDataSource1.Data = _testLib.GetGridXML(_Num)
GridView1.DataBind()
End Sub
where _testLib.GetGridXML is a function that returns an XML string based on the _Num passed in.

It's difficult to say without seeing your code... I would speculate that you assign the Data conditionally, i.e:
If Not IsPostBack Then
MyXMLDataSource.Data = "...some xml..."
End If
In this case it will be empty on post back and you get your exception. Could be something else, but then again, no code...
Update
Since you've added more information...
You must have something like code above on Page_Load. Since you are not providing it here, I presume you do. If you don't, you'd get the null reference exception on each load.
With that in mind, you assign data on some button click, but not on PageIndexChanging.
You click the button, the page loads, you assign the data, the grid shows it. Then you click the grid's next link, the page loads again, PageIndexChanging gets fired, your click event doesn't -- where's assignment then?
From what I see, either assign the Data property on Page_Load every time or do it in all subsequent events, i.e. on page change, on sort, etc.
Btw, you don't have to call DataBind when assigning XmlDataSource declaratively.

It should work if you do your databinding on the PreRender event
Since the XML datasource is being set dynamically if you set it on the PageLoad all the page elements might not exist at this stage.

Are you implelenting the OnPageChanging Event ? Normally you need to implement it and use the e.NewPageIndex property from the Event Argument to set it in your gridview.

Related

Asp.net textbox returns empty string when enter key is pressed at the end of text vb.net

I am very new to the world of aspx, web forms. But I am assigned to development of webform due to some circumstances. I am somehow struggling and surviving in this. I have a problem, may be if someone who is familiar with this, can help me understand is very much appreciable.
Problem:
I am created a search box functionality successfully in an aspx webform with codebehind as vb. But the problem is, when I type some text in this search box and press enter, it reloads to initial state rather than show up the search results. It works well when we just type text in it and do not press enter. For every letter I type in the box, in displays with matching search results. I just am wondering why is this not working if I type text and press enter at the end of text for example like google search. For ex: I typed "test" in searchbox and press enter. Results appear perfect until I press enter key. Once I press enter, it goes back to original state how ever it was.
Investigation:
I debugged it and found that when enter is pressed, the value in textbox becomes empty. I am unable to understand why is it getting empty even if text is present in text box. I tried onkeypress="return event.keyCode!=13" in
<asp:TextBox ID="SearchTextBox" runat="server" onkeypress="return event.keyCode!=13" CssClass="txt"></asp:TextBox> so as not to return empty value when enter is pressed. But it did not work.
Dim searchkey As String
searchkey = SearchTextBox.Text.
searchkey returns emtpy string and not "test" string. But why? How can I overcome it?
Looking for: Is there a possibility that I can get the text value present in textbox when enter is pressed.
I appreciate your help and new learning for me
Do not use onkeypress directly like this onkeypress="return event.keyCode!=13"
create a common js file and use it anywhere you want, you can modify also in one js.
use common js file and create a function and use on your code via link like this <script src="~/js/common.js"></script>
Here is the js code to prevent Enter key:
function DisbleEntr(evt) {
if (evt.key == "Enter") {
return false;
}}
and use in your code like this:
<asp:TextBox ID="SearchTextBox" runat="server" onkeypress="return DisbleEntr(event);" CssClass="txt"></asp:TextBox>
hope this will help you
Well, first up, enter key tends to mean submit the page.
And ALSO note that a simple hit of the enter key will trigger the FIRST button found on that page!!!!
Say we have this simple grid and at the bottom I have a search box, and a search button. Real simple, say like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table table-striped" Width="50%">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Edit Hotel" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdEdit" runat="server"
Text="Edit" CssClass="btn" OnClick="cmdEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="Label1" runat="server" Text="Search For Hotel" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:10px"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server"
Text="Search" Style="margin-left:10px"
CssClass="btn" />
Now, code to load above say this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
MyEditHotelC.ShowGrid(True)
End If
End Sub
Sub LoadGrid()
Dim rstData As DataTable
rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName")
GridView1.DataSource = rstData
GridView1.DataBind()
End Sub
Note SUPER DUPER VERY VERY close - note in above, that on page load, I ALWAYS check for IsPostback.
Remember, for any button click or any post-back the page load event fires. Including any button click - so code that setups up a grid, setups text box, or ANYTHING? - you only want to run such code one time.
We see/have about 5 posts a week here in which someone drops in a combo box, selects a value, and clicks a button - and then the selected value goes away!!!
Why? Because they had code in the page load event to load up the combo box, and thus each and every time that setup code to load the combo box runs each time and blows out your combo box selection.
BIG HUGE LESSON:
Quite much EVERY web page you build that has ANY setup code will thus have the above If NotPostBack code stub. I recon the last 100+ pages I built work this way.
So, ALWAYS make sure you include that If Not Postback stub for page setup code, and NEVER forget to do this.
Ok, so we run the page and we have this:
Now the first rule:
When you hit a enter key inside of a text box, the FIRST button on the page we find will trigger.
So, looking at above, what will happen?
Turns out the FIRST button on the page in tucked away in the GridView!!!!
So, if I type in to search box, and hit enter key, then this button will be clicked on:
Surprise!!!!
Now, why is this most of the time never a issue?
Well, in most cases, you don't have a lot of buttons and I can/could fix above, by simple moving the search box, and button to the top, say like this:
So, it turns out by luck, we find in most cases this is not a issue.
And a slick easy way to fix this issue?
Well, drop in a button at the VERY top of the page - set style = "display:none" (to hide the button, and this issue is fixed - all without any special code).
eg this:
<form id="form1" runat="server">
<asp:Button ID="catchEnter" runat="server" Text="Button"
OnClientClick="return false" style="display:none"/>
So, VERY first control on page.
next up:
So, VERY much keep the above in mind.
Next issue:
For every letter I type in the box, in displays with matching search results.
Ok, so you have some type of auto-complete code. That is a HUGE issue - and there are about 20+ libraries and examples floating around on the internet. You don't mention what code library you adopted (maybe the one from jQuery.UI, maybe the one from the ajaxtoolkit - but boatloads of systems exist).
Or MAYBE you rolled your own? I actually VERY high recommend the ajaxtoolkit, since it has a really nice autocomplete extender - and it uses ajax calls without postbacks for this setup.
Your issue is thus above and in summary:
The text box has some library code attached - gets setup in page load - but you failed to adopt and is the IsPostBack = false test.
The enter key not being trapped - and thus above - first button ANYWHERE in the page - even those tucked away in a grid view or anywhere else is thus causing a page post-back.
You not shared if your auto complete setup DOES a post-back, but again if it does, then that's often the issue.
So to prevent enter key clicking on first button, you can add the above "trick" and drop in a hidden button, and one that when clicked on does not cause a post-back due to enter key.
Since I have the ajax tool kit installed?
I can do this:
I choose Add extender for that text box, and choose this:
So, it puts in this markup for me:
<ajaxToolkit:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
BehaviorID="txtSearch_AutoComplete"
DelimiterCharacters=""
ServiceMethod="SearchCustomers"
MinimumPrefixLength="1"
CompletionInterval="100"
EnableCaching="false"
CompletionSetCount="40"
TargetControlID="txtSearch">
</ajaxToolkit:AutoCompleteExtender>
Nice about above? I can set how many chars before search. I can set the timign to update etc. And I not had to write one line of js code either!!!
So the above looks like this now
So, the only part I had to setup and write was the code behind for this search.
That was this:
<WebMethod()>
Public Shared Function SearchCustomers(ByVal prefixText As String, ByVal count As Integer) As List(Of String)
Using conn As SqlConnection = New SqlConnection()
conn.ConnectionString = My.Settings.TEST4
Using cmd As SqlCommand = New SqlCommand()
cmd.CommandText = "select HotelName from tblHotels where HotelName like #SearchText + '%'
ORDER BY HotelName"
cmd.Parameters.AddWithValue("#SearchText", prefixText)
cmd.Connection = conn
conn.Open()
Dim customers As List(Of String) = New List(Of String)()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(sdr("HotelName").ToString())
End While
End Using
conn.Close()
Return customers
End Using
End Using
End Function
But, all the rest? No extra code.
So, I would consider to adopt a stadnard library (jquery.UI maybe, or the above ajaxtoolkit).

ASP.NET GridView empty on postback

Having an issue with an ASP.NET GridView is empty on postback that I need some help with. I think it may have something to do with the ViewState not being setup. Anyhow I originally had the code working on single user-form until I refactored code.
Now to paint the picture I have now both a master page and a base form. My master page has the place holder and on my actual user-form I have placed the GridView within the place holder bounds as follows:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderMainBody" Runat="Server">
<asp:GridView ID="data" runat="server" AutoGenerateColumns="false" EnableViewState="true" ...>
...
</asp:GridView>
</asp:Content>
One of fields in the GridView is an editable comments field mutli-line textbox (the rest are non editable):
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:TextBox ID="TextBoxComments" runat="server" TextMode="MultiLine" Rows="4" Columns="40" Text='<%# Bind("Comment")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBoxCommentsEdit" runat="server" TextMode="MultiLine" Rows="4" Columns="40" Text='<%# Bind("Comment")%>' />
</EditItemTemplate>
</asp:TemplateField>
I edit one of the rows and click a submit button to postback. The GridView has 10 rows to enter into however on postback there are zero rows so my saving is lost!
My base form contains the code in the OnInit event to load the submit button and thus also handles the click event.
My OnLoad event I call the base Onload which inturn calls my user form's Page_Load handler code which has one line of code namely:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
MyBase.data = Me.data
End Sub
and in the BaseForm is declared as:
Protected WithEvents data As GridView
Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
If Not Page.IsPostBack Then
...
BindData(...)
...
End If
End Sub
in this way I can also handle all GridView events in the BaseForm.
So somewhere between the master/baseform/userform/viewstate relationship my GridView data is lost on PostBack. Any ideas?
On your Page_Load, bind the data only if IsPostBack is false.
You click on submit button that submit button fire RowUpdating event and that event contain query for update database table and after executed update query call BindData() function in your code .
Three in row I think for myself answering my own question - hooray! I do not know if that makes me intelligent or dumb because I have to search for more that a day to find a solution. Perhaps I did not give out enough information or it was not clear and this is what happens when you do things for the first time and you do not have a clue what you are doing. The vital information which was maybe not implied but hinted at, which I will spell it out for anyone else that might have the same problem, is I left out mentioning in my OnInit method I call the following code:
Dim cpl As ContentPlaceHolder = Master.FindControl("ContentPlaceHolderFooter")
btnUpdate = New Button
btn.ID = "btnUpdate"
cpl.Controls.Add(btnUpdate)
I know the purest will say why did you not add the button to the footer of the grid as opposed to an additional content placeholder in the master page - well with egg on my face I didn't.
Anyhow I moved the code above to the CreateChildControls overridable method and I also required an additional call to EnsureChildControls in my OnLoad event so my OnInit method with emphasis disintegrated!##%^* Why? Well the answer was hinted at within the answer to the other question asked on this site I mentioned in my second comment to "Rajan Chauhan" that I checked out and that is apparently whenever you iterate through the collection of controls you mess with the ViewState (hey I am just re-iterating what was said in the other post I have no authority on the matter) before it gets loaded so calling Master.FindControl is a no-no inside OnInit!
However, saying all that my RowUpdated event does not fire as I am actually editing in view mode because of my ItemTemplate markup so I will stick with what I have as my btnUpdate_Click event still works as before i.e. it does some magical code that I found on some other site that checks each row one by one for change of data and then updates that particular row only. Well I can as there is only 10 rows at most so I do not overload the ViewState too much and if it is important to know I also use paging so in reality I have more than 10 rows but did not want to mention that as I thought that might add to the confusion.

Can't access checkbox values in gridview on postback

This sounds a lot like a bunch of other questions on here, but nothing I've read follows what I'm seeing.
I have a gridview that contains a number of bound fields and a couple of template fields containing checkboxes. The gridview is bound to a custom datasource on pageload (inside a "not page.ispostback()" condition). The user can check the checkboxes to specify certain actions that are then committed when a link button is clicked.
The link button's click event has the following code in it:
For Each row As GridViewRow In UnpaidEntriesGridView.Rows
Dim paidCheckbox As CheckBox = CType(row.FindControl("PaidCheckbox"), CheckBox)
If paidCheckbox.Checked Then
// perform database action
End If
Next
Initialise() // (this rebinds the gridview)
No matter what I do, I cannot get hold of the checked value of any checkbox in the gridview that the user has changed. All checkboxes remain in their original state (set on data bind).
This is more than likely a page life-cycle issue, but for the life of me, I can't figure out why the user's changes aren't persisted after postback, despite the fact that the gridview isn't rebound until after I've checked.
ViewState is enabled, everything's pretty standard here otherwise.
Gridview code snippet from ascx follows:
<asp:GridView ID="UnpaidEntriesGridView" runat="server" AutoGenerateColumns="false" EnableViewState="true">
<Columns>
<asp:BoundField HeaderText="Entry Name" DataField="EntryName" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="PaidCheckbox" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinkButton ID="UnpaidEntriesSaveLinkButton" runat="server" Text="Commit Changes" />
Any help (even a slap for being so stupid) would be massively appreciated.

ASP.NET Repeater - HiddenField working without being declared

Using ASP.NET 4.0
Bit of a strange one here, my code works but I don't know why!
So I have some HTML like so:
<asp:Repeater runat="server" ID="uxMyRepeater" ClientIDMode="Predictable">
<ItemTemplate>
<asp:Button runat="server" Text="Submit" />
<asp:HiddenField runat="server" ID="uxIsVisibleHiddenField" Value="0" />
</ItemTemplate>
</asp:Repeater>
And the back end:
Protected Sub uxMyRepeater_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles uxMyRepeater.ItemCommand
uxIsVisibleHiddenField.Value = "1"
End Sub
So for some reason this works, usually I would expect to have to declare uxIsVisibleHiddenField in uxMyRepeater_ItemCommand like so:
Dim uxIsVisibleHiddenField As HiddenField = DirectCast(e.Item.FindControl("uxIsVisibleHiddenField"), HiddenField)
But in this particular case it works without the declarative statement. Can anyone shed any light on why it would do this?
Please note this is sample code only, not my actual code.
EDIT
Forgot to mention there is an UpdatePanel around each RepeaterItem, removing this causes Visual Studio to give me an error that'd I'd expect: 'uxIsVisibleHiddenField' is not declared. It may be inaccessible due to its protection level.
This could only happen if you have a control with the same ID that sits outside of the repeater. You won't have ID clashes because the repeater is a naming container.
Do you have any AlternatingItemTemplate ? It might be declared in that particular area and remained unnoticed.
After a lot of debugging the only thing I can say is that when I have an UpdatePanel inside the Repeaters ItemTemplate I don't need to declare the controls inside the ItemTemplate when accessing them in the DataBind event, very strange. Taking out the UpdatePanel causes complier errors so the UpdatePanel must be doing some auto hook-up between the Repeater and the controls.
Thanks for all your suggestions.

ASP.NET DropDownList not getting correct SelectedItem

We are using ASP.NET for one of our projects. However, when we are trying to read the SelectedItem or SelectedValue property of the DropDownList we are using in the callback function of a Link click, we are not getting the correct SelectedItem.
<FooterTemplate>
<asp:DropDownList ID="cmbTesters" ClientIDMode="Static" runat="server" Width="300px" DataSource='<%# PopulateTesterNames() %>' DataTextField="FullName" DataValueField = "PK_ID"></asp:DropDownList>
</FooterTemplate>
This is the DropDownList in the aspx file. The drop down is present within a GridView's Footer Row. We are invoking the following set of code on clicking a link.
if (int.TryParse(((DropDownList)dgCreateCPRVerificationResponse.FooterRow.FindControl("cmbTesters")).SelectedValue, out TesterID))
{
TesterID = int.Parse(((DropDownList)dgCreateCPRVerificationResponse.FooterRow.FindControl("cmbTesters")).SelectedValue);
}
The problem we are facing is that whatever value we choose, the SelectedValue is always of the first item in the list. We are using REST based URL defined in the global.asax file. Also note that this is not built on any framework.
Please help as soon as possible
Make sure to put the binding methods of the dropdownlist and the gridview inside if (!IsPostBack)

Resources