I have a GridView that shows particular data list or reports when clicking Generate button.
GridView Records
When I'm moving to the next page of the GridView or when I click the next page, the GridView binding becomes empty and it shows no GridView list.
Page Index Changed
Here's my code in .aspx
<asp:GridView ID="GridView1"
runat="server"
CellPadding="4"
HeaderStyle-ForeColor="White"
ForeColor="#333333"
GridLines="None"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt"
RowStyle-CssClass="row"
AllowSorting="True"
AllowPaging="True"
PageSize="25" Visible="false" OnRowDataBound="GridView1_RowDataBound"
EnableViewState="false">
<EmptyDataTemplate>
No record found.
</EmptyDataTemplate>
</asp:GridView>
Here's my code for Page_Load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
userid = IIf(SessionHandler.UserID = "", User.Identity.Name.ToUpper, SessionHandler.UserID)
V3Substance.Attributes.Add("onfocus", "javascript:if (this.value=='Substance Cas Number') { this.value = ''; }")
V3Substance.Attributes.Add("onblur", "javascript:if (this.value=='') { this.value = 'Substance Cas Number'; }")
If Not Page.IsPostBack Then
V1Division.DataSource = GetDivision()
V1Division.DataBind()
V1BR.Items.Clear()
V1BR.DataSource = GetBusinessRule(V1Division.Text)
V1BR.DataBind()
MultiView1.ActiveViewIndex = 0
Panel1.DefaultButton = "V1Generate"
End If
End Sub
Here's my code for GridView1_PageIndexChanging
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
Dim dt As DataTable = TryCast(GridView1.DataSource, DataTable)
GridView1.DataSource = SortTable(dt)
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()
End Sub
And here's my code for BindGridView
Private Sub BindGridview(ByVal query As String, ByVal countquery As String)
ViewState.Add("Query", query)
ViewState.Add("CountQuery", countquery)
Dim count As Integer = 0
If Description.Text = "1" Then
ValidateFamily(query)
Else
DataSource = dbHelper.GetRecordDT(query)
End If
count = DataSource.Rows.Count
'GridView1.DataSource = Nothing
'GridView1.DataBind()
'GridView1.PageIndex = 0
GridView1.DataSource = DataSource
GridView1.Visible = True
GridView1.DataBind()
ExportToExcel.Visible = IIf(count < 1, False, True)
Panel1.Visible = IIf(count < 1, False, True)
SetTotalResult(count)
End Sub
I hope you can help me with this. I can't seem to know what could be the problem. I tried different approach to this and find a solutions from the internet but it didn't help. Thanks a lot.
You should be using
GridView1.DataSource = DataSource
It's unclear from your snippet what DataSource is, but you use it in the BindGridview method also.
Start using different names for variables, naming them exactly as properties is very confusing and will lead to errors.
Update
Dim source As SqlDataSource
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
source = New SqlDataSource
source.ID = "mySource"
source.SelectCommand = "select * from table"
source.ConnectionString = connStr
If Not Page.IsPostBack Then
GridView1.DataSource = source
GridView1.DataBind
End If
End Sub
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
GridView1.DataSource = source
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind
End Sub
Related
i am not able to find the id of the update button is thee any way to
find the update button id which is inside the gridview and the grid is
inside the update panel.
Script register is written is page load. i am writing this so as
currently update button is firing on second click
ASPX code
<asp:UpdatePanel ID="UpdatePanelSubMeter" runat="server">
<ContentTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" Style="background-color: #B2DE94; width: 40px" CausesValidation="false" runat="server" OnClientClick="return fnCheck(this);" Text="Update" CommandName="Update" />
</EditItemTemplate>
</asp:UpdatePanel>
vb.net code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.ErrorLabel.Text = String.Empty
Me.ErrorLabel.Visible = False
Dim pageName = HttpContext.Current.Request.Url.AbsoluteUri
If (Not Page.IsPostBack) Then
tblNAbers.Visible = True
BindBLDGDropDown("adonepudi")
End If
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
end sub
Protected Sub ddlBldgId_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlBldgId.SelectedIndexChanged
If ddlBldgId.SelectedItem.Value != -1 Then
BindGridSubMeter()
end sub
Protected Sub BindGridSubMeter()
Dim conMRI As New ConnectionMRI()
Dim ds As DataSet = conMRI.NabersSubMetergetData(ddlBldgId.SelectedItem.Value, ddlRating.SelectedItem.Value)
TextExclusions.Text = ds.Tables(1).Rows(0).Item(0).ToString()
UpdatePanelExclusions.update()
With GridSubMeter
.DataSource = ds.Tables(0)
.DataBind()
End With
End Sub
Protected Sub GridSubMeter_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridSubMeter.RowEditing
GridSubMeter.EditIndex = e.NewEditIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubmeter_PageIndexChanging(sender As Object, e4 As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridSubMeter.PageIndexChanging
GridSubMeter.PageIndex = e4.NewPageIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubMeter_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridSubMeter.RowUpdating
Dim txtMeterIdn As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txtMeterIdn"), TextBox)
Dim txCTFact As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txCTFact"), TextBox)
Dim txReadStartDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadStartDate"), TextBox)
Dim txReadEndDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadEndDate"), TextBox)
Dim txStartKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txStartKwh"), TextBox)
Dim txEndKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txEndKwh"), TextBox)
Dim txBillPer As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txBillPer"), TextBox)
Dim MeterIdn As String = txtMeterIdn.Text.Trim.ToString()
Dim CTFact As Decimal = Convert.ToDecimal(txCTFact.Text)
Dim ReadStartDate As Date = Date.Parse(txReadStartDate.Text)
Dim ReadEndDate As Date = Date.Parse(txReadEndDate.Text)
Dim StartKwh As Decimal = Convert.ToDecimal(txStartKwh.Text)
Dim EndKwh As Decimal = Convert.ToDecimal(txEndKwh.Text)
Dim billper As Decimal = Convert.ToDecimal(txBillPer.Text)
Dim leasid As String = GridSubMeter.Rows(e.RowIndex).Cells(0).Text.Trim.ToString()
Dim suitid As String = GridSubMeter.Rows(e.RowIndex).Cells(1).Text.Trim.ToString()
Dim occupant As String = GridSubMeter.Rows(e.RowIndex).Cells(2).Text.Trim.ToString()
GridSubMeter.EditIndex = -1
Dim conMRI As New ConnectionMRI()
conMRI.NaberSubmeter(ddlBldgId.SelectedItem.Value, leasid, suitid, occupant, MeterIdn, CTFact, ReadStartDate, ReadEndDate, StartKwh, EndKwh, billper)
Me.BindGridSubMeter()
End Sub
Try removing
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
from page load and paste it in BindGridSubMeter at the end.
Try this
For Each gr As GridViewRow In Grid_Records.Rows
Dim bt As Button = DirectCast(gr.Cells(0).FindControl("btn_Update"), Button)
Dim here As bt.properties
Next
I have the following code in the page source:
<asp:Button ID="Button1" runat="server" Text="Button" />
And in code behind page:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 9
Dim box As New TextBox()
box.ID = "textBox" + CStr(i)
box.Width = 20
box.Text = CStr(i)
box.TabIndex = CShort(i + 1)
AddHandler box.TextChanged, AddressOf ClickBox
panel1.Controls.Add(box)
Next
End Sub
Private Sub ClickBox(sender As Object, e As EventArgs)
Dim boxUsed = DirectCast(sender, TextBox)
boxUsed.BackColor = Drawing.Color.Crimson
End Sub
The problem is TextChange event for texboxes doesn't fire.
Two things. First:
box.AutoPostBack = True
Second:
Since you're creating textboxes dynamically, they will be gone between every postback, unless you re-create them in the Page_Load event.
I am trying to take an array of string (Filled from a listbox on a previous page and passed via Session) and display it in a label,this is how i got the array:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim x = ListBox1.GetSelectedIndices.Count
Dim ListPNames(x) As String
Dim i As Integer
i = 0
For Each item As String In ListBox1.GetSelectedIndices
ListPNames(i) = (ListBox1.SelectedItem).ToString
i = i + 1
Next
Session("SlctdPhones") = ListPNames(x)
Response.Redirect("CheckOut.aspx")
End Sub
And this is how i am trying to display it :
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim i As Integer
Label3.Text = ""
For i = 0 To SlctdPhones.Length - 1
Label3.Text += SlctdPhones(i).ToString() + Environment.NewLine
Next
End Sub
It is giving me an error :Object reference not set to an instance of an object. when it reaches the SlctdPhones.Length - 1 Line!!
i don't know how i can fix it ,also is my array code correct(Is everything being stored correctly in it?)
You declare the For loop like this:
For Each item In ...
But then never use the item variable in the body of the loop. Instead, you keep using the same SelectedItem property. You want to change that whole method to look like this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim PNames As New List(Of String)()
For Each index As Integer In ListBox1.GetSelectedIndices
PNames.Add(ListBox1.Items(index).Value)
Next
Session("SlctdPhones") = PNames
Response.Redirect("CheckOut.aspx")
End Sub
With that fixed, the Page_Load can do this:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones As List(Of String) = TryCast(Session.Item("SlctdPhones"), List(Of String))
If SlctdPhones Is Nothing OrElse SlctdPhones.Length = 0 Then
'Something went wrong here!
Return
End If
Label3.Text = String.Join("<br/>", SlctdPhones.ToArray())
End Sub
But I'd really love to see you use a data control rather than stuffing <br/>s into a label. Here's markup for a ListView:
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><%# Container.DataItem.ToString() %></li>
</ItemTemplate>
<EmptyDataTemplate>
<p>Nothing here.</p>
</EmptyDataTemplate>
</asp:ListView>
And then Page_Load is even simpler:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.DataSource = Session.Item("SlctdPhones")
ListView1.DataBind()
End Sub
On display page, use Literal instead of Label
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim result as String = string.Join("<br>", SlctdPhones) 'Instead of <br> try Environment.NewLine as well
YourLitetal = result
Hope this helps!
I am trying to update GridView with a lot of records through an ObjectDataSource. I am only updating the changed records, so I use ViewState to check if the original datatable has changed. It works fine on my localhost/IIS but when I try the same solution on the deployment server it gives me an error:
Index was outside the bounds of the array.
In this line of code:
Dim row As System.Data.DataRow = originalDataTable.Select(String.Format("ID = '{0}'", currentID))(0)
Below is an example of my code. Is there a problem with ViewState on the server?
Private ProdNum As String
Private tableCopied As Boolean = False
Private originalDataTable As System.Data.DataTable
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If Not tableCopied Then
originalDataTable = CType(e.Row.DataItem, System.Data.DataRowView).Row.Table.Copy()
ViewState("originalValuesDataTable") = originalDataTable
tableCopied = True
End If
End If
End Sub
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click, btnUpdate1.Click
originalDataTable = CType(ViewState("originalValuesDataTable"), System.Data.DataTable)
For Each r As GridViewRow In GridView1.Rows
If IsRowModified(r) Then GridView1.UpdateRow(r.RowIndex, False)
Next
' Rebind the Grid to repopulate the original values table.
tableCopied = False
GridView1.DataBind()
End Sub
Protected Function IsRowModified(ByVal r As GridViewRow) As Boolean
Dim currentID As Guid
Dim currentNyhed as Boolean
currentID = Guid.Parse(GridView1.DataKeys(r.RowIndex).Value.ToString())
currentNyhed = CType(r.FindControl("CheckBoxNews"), CheckBox).Checked
Dim row As System.Data.DataRow = originalDataTable.Select(String.Format("ID = '{0}'", currentID))(0)
If Not currentNyhed.Equals(row("News").ToString()) Then Return True
Return False
End Function
The GridView is bound to an ObjectDataSource with these basic settings:
<asp:ObjectDataSource ID="ObjectDataSource1" ViewStateMode="Enabled" EnableViewState="true" runat="server" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetDataByOverruled" TypeName="DSoverskrivslisteTableAdapters.Shop_Products_Egenskaber_OverrulingTableAdapter" UpdateMethod="Update">
The whole thing is based on this tutorial below. Instead of SqlDataSource I am using the ObjectDataSource which - as mentioned - works fine when run on my localhost, but gives me the error when uploaded to the deployment server.
http://msdn.microsoft.com/en-us/library/aa992036(v=vs.90).aspx
Please help.
I can not manage to get the gridview display the total in a footer
I've tried the following:
<asp:GridView ID="GV" runat="server"
DataSourceID="SqlQuery" EmptyDataText="No data">
<Columns>
<asp:BoundField DataField="Weekday" FooterText=" " HeaderText="Weekday" />
<asp:BoundField DataField="Volume" DataFormatString="{0:N0}"
FooterText="." HeaderText="Volume" />
</Columns>
</asp:GridView>
Protected Sub GV_rowdatabound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound
Dim Volume as integer = 0
For Each r As GridViewRow In GV.Rows
If r.RowType = DataControlRowType.DataRow Then
Volume = Volume + CDec(r.Cells(1).Text)
End If
Next
GV.FooterRow.Cells(1).Text = Math.Round(Volume , 0)
End Sub
This gives me an error messages:
Object reference not set to an instance of an object
I followed advice in the following page and I changed the code:
trying to total gridview in asp
Sub GV_WeekSumary_rowcreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim Volume as integer = 0
For Each r As GridViewRow In GV.Rows
If r.RowType = DataControlRowType.DataRow Then
Volume = Volume + CDec(r.Cells(1).Text)
End If
Next
If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(1).Text = Math.Round(Volume , 0)
End If
End Sub
This does not give an error, but the footer does not show any value.
I've tried also the following:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Volume as integer = 0
For Each r As GridViewRow In GV.Rows
If r.RowType = DataControlRowType.DataRow Then
Volume = Volume + CDec(r.Cells(1).Text)
End If
Next
GV.FooterRow.Cells(1).Text = Math.Round(Volume, 0)
GV.DataBind()
End Sub
Still no value in the footer, but when I debbug it I can see that footer is assisgned the value I need. Why it is not displayed in the website?
Any idea how I can get this to work?
You must use DataBound event.
Try this:
Protected Sub GV_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GV.DataBound
Dim Volume As Decimal = 0
For Each r As GridViewRow In GV.Rows
If r.RowType = DataControlRowType.DataRow Then
Volume += Convert.ToDecimal(r.Cells(1).Text)
End If
Next
GV.FooterRow.Cells(1).Text = Math.Round(Volume, 0).ToString()
End Sub