I'm new to asp.net and have recently been working with creating a GridView from codebehind to make it more flexible so that I can eventually have it created based on user specifications.
Now I'm exploring classes, and I thought it would be cool to create a GridView class so that whenever I need to make a GridView I can just pass the class my specifications instead of having the same code re-written on each page's codebehind.
I'm not really seeing too many examples of how to accomplish this though. Have any of you done this? Does it even make sense for me to do this?
Here's how I'm currently making my GridView with codebehind. Any idea how I can change this to create the GridView with a class?
.aspx page:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
EmptyDataText="There are no data records to display." AllowPaging="True"
CssClass="GridViewStyle" GridLines="None" Width="100%">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="EmployeeID"
DataNavigateUrlFormatString="EmployeeProfile.aspx?EmployeeID={0}"
DataTextField="EmployeeID"
DataTextFormatString= "<img src='Images/icons/document-search-result.png' alt='View'/> <u>View</u>" >
<ControlStyle CssClass="titleLinksB" />
<ItemStyle Wrap="False" />
</asp:HyperLinkField>
</Columns>
<RowStyle CssClass="RowStyle" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
<PagerSettings Mode="NumericFirstLast" PageButtonCount="5" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedRowStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<EditRowStyle CssClass="EditRowStyle" />
<AlternatingRowStyle CssClass="AltRowStyle" />
<SortedAscendingHeaderStyle CssClass="sortasc"></SortedAscendingHeaderStyle>
<SortedDescendingHeaderStyle CssClass="sortdesc"></SortedDescendingHeaderStyle>
</asp:GridView>
.aspx.vb Code-behind page:
Partial Class GridTest2
Inherits System.Web.UI.Page
Sub Page_load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CreateGridColumns()
BindGrid()
End If
End Sub
Public Property SortExpression As String
Get
If ViewState("SortExpression") Is Nothing Then
ViewState("SortExpression") = "LastName ASC"
End If
Return ViewState("SortExpression").ToString
End Get
Set(ByVal value As String)
ViewState("SortExpression") = value
End Set
End Property
Private Sub CreateGridColumns()
Dim curLastName As New BoundField
curLastName.HeaderText = "Last Name"
curLastName.DataField = "LastName"
curLastName.SortExpression = "LastName"
GridView1.Columns.Insert(0, curLastName)
Dim curFirstName As New BoundField
curFirstName.HeaderText = "First Name"
curFirstName.DataField = "FirstName"
curFirstName.SortExpression = "FirstName"
GridView1.Columns.Insert(1, curFirstName)
End Sub
Private Sub BindGrid()
Try
Dim tblData = New DataTable
Using sqlCon As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("dbConnectionString").ConnectionString.ToString())
Dim sql As String = "SELECT * FROM Employees"
Dim sqlCmd = New SqlClient.SqlCommand()
sqlCmd.CommandText = String.Format(sql, Me.SortExpression)
sqlCmd.Connection = sqlCon
Using objAdapter As New SqlClient.SqlDataAdapter(sqlCmd)
objAdapter.Fill(tblData)
End Using
End Using
GridView1.DataSource = tblData
GridView1.DataBind()
GridView1.HeaderRow.CssClass = "HeaderStyle"
Catch ex As Exception
' TODO: log error '
Throw
End Try
End Sub
Private Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
Me.GridView1.PageIndex = e.NewPageIndex
BindGrid()
End Sub
Protected Sub GridView1_RowDataBound1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
'Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim gridView As GridView = DirectCast(sender, GridView)
Dim sortColumn As String, sortDirection As String
sortColumn = Me.SortExpression.Split(" "c)(0)
sortDirection = Me.SortExpression.Split(" "c)(1)
If e.Row.RowType = DataControlRowType.Header Then
Dim cellIndex As Integer = -1
For Each field As DataControlField In gridView.Columns
If field.SortExpression = sortColumn Then
cellIndex = gridView.Columns.IndexOf(field)
End If
Next
If cellIndex > -1 Then
' this is a header row, set the sort style
e.Row.Cells(cellIndex).CssClass = If(sortDirection = "ASC", "sortasc", "sortdesc")
End If
End If
End Sub
Private Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
Dim currentSortColumn, currentSortDirection As String
currentSortColumn = Me.SortExpression.Split(" "c)(0)
currentSortDirection = Me.SortExpression.Split(" "c)(1)
If e.SortExpression.Equals(currentSortColumn) Then
' switch sort direction '
Select Case currentSortDirection.ToUpper
Case "ASC"
Me.SortExpression = currentSortColumn & " DESC"
Case "DESC"
Me.SortExpression = currentSortColumn & " ASC"
End Select
Else
Me.SortExpression = e.SortExpression & " ASC"
End If
BindGrid()
End Sub
End Class
Any help is greatly appreciated!
If i understand correctly you are trying to make Custom Gridview class. you can follow below links for your help. All you need to do is make a class which inherits Gridview class so that you override default functionality to make it more generic.
Extending the GridView Control
Custom Gridview with paging and filtering
Creating Custom Gridview Control
Related
I have a GridView with Paging and Programatically Databind it on Page_Load. Also I have a search button that when clicked it databinds to a diferent sql command. If you click the search button and it retrieve more than one page and if you click on page 2 it retrieves the data of the first Databind(). How can I fix that using the GridView1.PageIndexChanging which is what I'm using for paging on the first Databind? Anyhelp would be very appreciated. Is it even posible?
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" PageSize="100">
<Columns>
<asp:BoundField DataField="fldEmployeeID" HeaderText="EmployeeID" />
<asp:BoundField DataField="fldAbsentDate" HeaderText="AbsentDate" />
<asp:BoundField DataField="fldAbsentCode" HeaderText="AbsentCode" />
<asp:BoundField DataField="fldRuleViolationWarningType" HeaderText="Rule Violation Warning" />
<asp:BoundField DataField="fldRuleViolationIssueDate" HeaderText="Rule Violation Issue Date" />
<asp:BoundField DataField="fldLOAEndDate" HeaderText="LOA End Date" />
</Columns>
</asp:GridView>
vb.net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim SqlDataSource1 As SqlDataSource = New SqlDataSource()
SqlDataSource1.ID = "SqlDataSource1"
Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = "your connection string"
'SqlDataSource1.SelectCommand = "SELECT * FROM [tblAbsences] WHERE [fldEmployeeID]=38"
SqlDataSource1.SelectCommand = "SELECT * FROM [tblAbsences] ORDER BY [fldEmployeeID], [fldAbsentDate], [fldAbsentCode]"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End Sub
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles GridView1.PageIndexChanging
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SqlDataSource2 As SqlDataSource = New SqlDataSource()
SqlDataSource2.ID = "SqlDataSource2"
Page.Controls.Add(SqlDataSource2)
SqlDataSource2.ConnectionString = "your connection string"
SqlDataSource2.SelectCommand = "SELECT * FROM [tblAbsences] WHERE [fldAbsentDate] BETWEEN '7-03-2014' AND '8-21-2014' ORDER BY [fldAbsentDate]"
'SqlDataSource2.SelectCommand = "SELECT * FROM [tblAbsences] ORDER BY [fldEmployeeID], [fldAbsentDate], [fldAbsentCode]";
GridView1.DataSource = SqlDataSource2
GridView1.DataBind()
End Sub
Add an invisible html label/textbox into your main form...
<asp:label runat="Server" ID="SDS2" visible="false" text="0" />
Page Load would look like the following, and would likely benefit from having the SDS2 added to it as well in an 'else' clause in the same IF statement.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If SDS2.Text = "0"
Dim SqlDataSource1 As SqlDataSource = New SqlDataSource()
SqlDataSource1.ID = "SqlDataSource1"
Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = "your connection string"
'SqlDataSource1.SelectCommand = "SELECT * FROM [tblAbsences] WHERE [fldEmployeeID]=38"
SqlDataSource1.SelectCommand = "SELECT * FROM [tblAbsences] ORDER BY [fldEmployeeID], [fldAbsentDate], [fldAbsentCode]"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
Else
'Call the SDS2 stuff here
End If
End Sub
And in your button click handler add this line to set it to use SDS2 instead.
SDS2.Text = "1"
I have a Windows form with 1 DataGrid which has a Dropdownlist in one of its columns.
I also have another dropDownlist outside of this DataGrid.
Both of these dropdowns are bound to same dataset and both get populated with same items.
Both of DropDowns have their Autopostbacks set to true.
Problem is only for the dropdownlist Outside of Datagrid SelectedIndexChange Event gets fired:
(I have seen multiple similar questions on SO but none of suggestions works for me. So I really appreciate if you can help me here.
)
Protected Sub ABCD(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
For both Dropdownlists: AutoPostBack="True"
Here is Vb code:
Imports System.Data.OleDb
Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents dg As New System.Web.UI.WebControls.DataGrid
Private cnDB As New OleDbConnection
Private ds As New DataSet
Private daDB As New OleDbDataAdapter
Protected allNames As New DataSet
Protected MyDataSet As DataSet
Protected WithEvents DropDownList1 As System.Web.UI.WebControls.DropDownList
Protected WithEvents DropDownList2 As System.Web.UI.WebControls.DropDownList
Protected WithEvents ddlName As New System.Web.UI.WebControls.DropDownList
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MyDataSet = NameBudget()
GridDataLoad()
End Sub
Protected Sub Grid_EditCommand(ByVal source As Object, ByVal e As DataGridCommandEventArgs)
dg.EditItemIndex = e.Item.ItemIndex
dg.DataSource = ds
dg.DataBind()
End Sub
Protected Sub Grid_CancelCommand(ByVal source As Object, ByVal e As DataGridCommandEventArgs)
dg.DataSource = ds.Tables(0).DefaultView
dg.EditItemIndex = -1
dg.DataSource = ds
dg.DataBind()
End Sub
Protected Sub Grid_UpdateCommand(ByVal source As Object, ByVal e As DataGridCommandEventArgs)
End Sub
Private Function GridDataLoad()
ddlName.DataSource = MyDataSet
Dim i As Object = MyDataSet.Tables(0)
ddlName.DataBind()
DropDownList1.DataSource = MyDataSet
DropDownList1.DataBind()
Dim strCon As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\AccessTestDataBases\TestDB.mdb; "
Dim cnDB As New OleDbConnection(strCon)
cnDB.Open()
daDB = New OleDbDataAdapter("Select * from [Persons]", cnDB)
daDB.Fill(ds, "tbl1")
Dim j As Object = ds.Tables(0)
dg.DataSource = ds
dg.DataBind()
cnDB.Close()
Dim ii As Object = ds.Tables(0)
End Function
Protected Function NameEditable(ByVal n As String) As Boolean
Return True
End Function
Protected Function NameBudget() As DataSet
Dim strCon As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\AccessTestDataBases\TestDB.mdb; "
Dim cnDB As New OleDbConnection(strCon)
cnDB.Open()
daDB = New OleDbDataAdapter("Select ID,Name from [Persons]", cnDB)
Dim ds As New DataSet
daDB.Fill(ds, "tbl1")
cnDB.Close()
Return ds
End Function
Sub SetDefaultListItem(ByVal sender As Object, ByVal e As System.EventArgs)
'*************************************************************************
'* Use this sub to set the Default List for DropDown Listboxes *
'*************************************************************************
Try
If Len(sender.DefaultValue) > 0 Then
If sender.Items.FindByValue(sender.DefaultValue).ToString.Length > 0 Then
sender.Items.FindByValue(sender.DefaultValue).Selected = True
End If
End If
Catch ex As System.Exception
'Throw New System.Exception(ex.ToString())
End Try
End Sub
Protected Sub ABCD(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class
Here is the HTML for datagrid and Dropdownlists:
<Columns>
<ASP:ButtonColumn Text="Delete" CommandName="Delete"></ASP:ButtonColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel"
EditText="Edit"></asp:EditCommandColumn>
<ASP:TemplateColumn HeaderText="Name" SortExpression="FY" HeaderStyle-HorizontalAlign="center" HeaderStyle-Wrap="True">
<ItemStyle Wrap="false" HorizontalAlign="left" />
<ItemTemplate>
<ASP:Label ID="Name" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<ASP:DropDownList id="DropDownlist2" datasource="<%# MyDataSet %>" DataTextField= "Name" DataValueField="ID" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ABCD">
</ASP:DropDownList>
</EditItemTemplate>
</ASP:TemplateColumn>
</Columns>
<asp:DropDownList id="DropDownList1"
datasource="<%# MyDataSet %>" DataTextField= "Name"
DataValueField="ID" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ABCD">
</asp:DropDownList>
I am a AS400 programmer asked to write a program in asp.net using vb.net. I have never done this before and I am having issues with populating a listbox in Gridview. I have researched this subject for days but all the code I have tried, found in examples, do not work. Please forgive any really bad code, with me being so new to .net, I am sure this could be written much better. I appreciate any help you may be able to offer. the grid is "AdjusterList" and the Listbox is called "MAICD". I think the 'failing/bad' code in
Public Sub AdjusterList_RowDataBound. It is giving me a null exception error the line before the databind; oCtrl.DataSource = oRs
I am using code given to me by a senior .net programmer, whom is not able to offer any more assistance to this newbie. Just Fyi....
Here is my aspx.
<div id="div1" runat="server">
<asp:GridView ID="AdjusterList" runat="server" Width="1100px"
ClientIDMode="Static" AllowSorting="True"
AutoGenerateColumns="False"
OnRowCommand="AdjusterList_RowCommand"
OnRowEditing="AdjusterList_RowEditing"
OnRowUpdating="AdjusterList_RowUpdating"
OnRowDeleting="AdjusterList_RowDeleting"
OnRowCancelingEdit="AdjusterList_RowCancelingEdit"
OnRowDataBound="AdjusterList_RowDataBound"
DataKeyNames="INSCD, INSSEQ"
ShowHeaderWhenEmpty="True" EditRowStyle-BackColor="#FF9900" PageSize="20"
EmptyDataText="NO RECORDS FOUND FOR THIS INSURER"
ShowFooter="True"EnableViewState="true">
<EditRowStyle BackColor="#FF9900" />
<RowStyle BackColor="White" ForeColor="Black" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton id="btnedit" runat="server" CommandName="Edit"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton id="btnupdate" runat="server" CommandName="Update" Text="Save" />
<asp:LinkButton id="btncancel" runat="server" CommandName="Cancel" Text=Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton id="btninsert" runat="server" CommandName="Insert" Text="Insert"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Mail Code" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblmaicd" runat="server" Text='<%# Bind("MAICD")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:ListBox ID="MAICD" runat="server" Rows="1"DataTextField="Text"
DataValueField='<%# Bind("MAICD")%></asp:ListBox>
</EditItemTemplate>
<FooterTemplate>
<asp:ListBox ID="MAICD" runat="server" width="200" DataTextField="Text">
</asp:ListBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My code behind...
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class EditAdjusterData
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e AsSystem.EventArgs)
Dim sAdjuster As String = Session("Adjuster")
Dim sSeqNo As String = Session("SeqNo")
PopulateEdit(sAdjuster, sSeqNo, dateok)
If IsPostBack Then
'divEdit.Visible = False
'divSelect.Visible = True
'ShowForm()
Else
AdjusterList.DataBind()
'divEdit.Visible = True
'divSelect.Visible = False
End If
End Sub
Protected Sub PopulateEdit(sValue As String, sValue2 As String, sValue3 As String)
' CALL TO PGRTSTLIB FILE INSP TO GET INSURER NAME
' 2ND CALL TO PGRTSTLIB FILE INSD
Dim oConn As New OleDbConnection()
Dim sConn As String = ""
Dim oCmd As New OleDbCommand()
Dim oAdapter As New OleDbDataAdapter()
Dim oRs As DataSet = New DataSet
Dim sSql As String = ""
sConn = "Provider=IBMDA400.DataSource.1;
oConn = New OleDb.OleDbConnection(sConn)
oConn.Open()
sSql = "SELECT INSCD, INSSEQ, MAICD, MAISEQ, (substr(char(EFFDT),5,2) || '-' || substr(char(EFFDT),7,2) || '-' || substr(char(EFFDT),1,4)) AS EFFDT, (substr(char(CANDT),5,2) || '-' || substr(char(CANDT),7,2) || '-' || substr(char(CANDT),1,4)) AS CANDT, ACCFIL FROM PGRTSTLIB.INSD WHERE INSCD = '" & sValue & "' "
oCmd = New OleDbCommand(sSql, oConn)
Session(INSCD) = INSCD
Session(EFFDT) = EFFDT
Session(MAICD) = MAICD
Session("CANDT") = CANDT
oCmd.CommandType = CommandType.Text
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oRs, "Data")
Dim sMailCode As String = " "
Dim sMailSeq As String = " "
Dim pRow As DataRow
For Each pRow In oRs.Tables("Data").Rows
sMailCode = pRow("MAICD").ToString()
Next
Session(sMailCode) = MAICD
Session(MAICD) = sMailCode
Session(sMailCode) = sMailCode
AdjusterList.DataSource = oRs
'AdjusterList.DataBind()
'If sMailCode <> " " Then
' PopulateMailCode(sMailCode)
'End If
oRs.Dispose()
oAdapter.Dispose()
oCmd.Dispose()
oConn.Dispose()
End Sub
Protected Sub AdjusterList_PageIndexChanging(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
AdjusterList.PageIndex = e.NewPageIndex
AdjusterList.DataBind()
End Sub
Protected Sub AdjusterList_RowCommand(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
End Sub
Protected Sub AdjusterList_RowCreated(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
End Sub
Public Sub AdjusterList_RowDataBound(ByVal Sender As Object,
ByVal e As GridViewRowEventArgs) Handles AdjusterList.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.FindControl("MAICD") IsNot Nothing Then
Dim MAICD As ListBox = e.Row.FindControl("MAICD")
'If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
BindAjusterList()
End If
End If
End Sub
Public Sub BindAjusterList()
Dim oConn As New OleDbConnection()
Dim sConn As String = ""
Dim oCmd As New OleDbCommand()
Dim oAdapter As New OleDbDataAdapter()
Dim oRs As DataSet = New DataSet
Dim sSql As String = ""
sConn = "Provider=IBMDA400.DataSource.1; "
oConn = New OleDb.OleDbConnection(sConn)
oConn.Open()
'sSql = "SELECT MAICD as Value, MAICD AS Text from PGRTSTLIB.INSM order by MAICD"
sSql = "SELECT MAICD As Value, MAICD AS TEXT from PGRTSTLIB.INSM"
oCmd = New OleDbCommand(sSql, oConn)
'oCmd.Parameters.Add(New SqlParameter("#Type", Insurer))
oCmd.CommandType = CommandType.Text
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oRs, "ListBox")
Dim oCtrl As ListBox
oCtrl = AdjusterList.FindControl("MAICD")
oCtrl.Items.Add(New ListItem("", ""))
oCtrl.DataSource = oRs
oCtrl.DataBind()
oCtrl.Items.Insert(0, New ListItem(String.Empty, String.Empty))
If Len(sValue) > 0 Then
oCtrl.SelectedValue = sValue
Else
sValue = " "
End If
oRs.Dispose()
oAdapter.Dispose()
oCmd.Dispose()
oConn.Dispose()
End Sub
Public Sub AdjusterList_RowEditing(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
AdjusterList.EditIndex = e.NewEditIndex
AdjusterList.DataBind()
End Sub
Protected Sub AdjusterList_RowUpdating(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
' Dim row As GridViewRow = DirectCast(SubsidaryList.Rows(e.RowIndex), GridViewRow)
Dim INSCD As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells (0).FindControl ("INSCD"), TextBox).Text
Dim INSSEQ As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(1).FindControl("INSSEQ"), TextBox).Text
Dim MAICD As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(2).FindControl("MAICD"), ListBox).Text
Dim MAISEQ As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(3).FindControl("MAISEQ"), TextBox).Text
Dim EFFDT As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(4).FindControl("EFFDT"), TextBox).Text
Dim CANDT As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(5).FindControl("CANDT"), TextBox).Text
Dim ACCFIL As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(6).FindControl("ACCFIL"), TextBox).Text
AdjusterList.EditIndex = -1
AdjusterList.DataBind()
' New Data to DataBind to sql datasource and resend page after RECORD updated
Response.Redirect("EditAdjusterData.aspx")
End Sub
Protected Sub AdjusterList_RowCancelingEdit() Handles AdjusterList.RowCancelingEdit
AdjusterList.EditIndex = -1
AdjusterList.DataBind()
End Sub
End Class
I am so new to .net and I may not fully understand every example. I think the senior .net programmers think it is funny : (
Thanks so much and please feel free to contact me with any help you may be able to offer. I just need the darn listbox to populate. I removed any code I considered unrelated to this listbox issue.
In your markup, you should change the DataValueField property of your ListBox to the "Value" string, because it's the alias you are giving to the property in the query ("SELECT MAICD As Value, MAICD AS TEXT from PGRTSTLIB.INSM"):
<asp:ListBox ID="MAICD" runat="server" Rows="1"DataTextField="Text" DataValueField="Value"></asp:ListBox>
Also, in RowDataBound event, you are retrieving the ListBox instance for that row using the FindControl method, but then you are retrieving it again in the BindAjusterList() method. Try changing the method to receive the control found:
Public Sub AdjusterList_RowDataBound(ByVal Sender As Object, ByVal e As GridViewRowEventArgs) Handles AdjusterList.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.FindControl("MAICD") IsNot Nothing Then
Dim MAICD As ListBox = e.Row.FindControl("MAICD")
BindAjusterList(MAICD)
End If
End If
End Sub
Public Sub BindAjusterList(ByVal oCtrl As ListBox)
' existing logic
oCtrl.Items.Add(New ListItem("", ""))
oCtrl.DataSource = oRs
oCtrl.DataBind()
' existing logic
End Sub
I am attempting to sort a gridview in an updatepanel. It compiles, but I get an Object reverence not set to an instance of an object error. I am trying to follow this guide, but in vb
default.aspx
<ajx:UpdatePanel ID="ajaxpanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False"
CssClass="gridview" DataKeyNames="ProgramNumber"
AllowPaging="True" PageSize="2" AllowSorting="True" OnSorting="gvProgramDetails_Sorting">
<Columns>
<asp:CommandField ControlStyle-CssClass="button delete" ShowDeleteButton="True">
<ControlStyle CssClass="button delete" />
</asp:CommandField>
<asp:CommandField ControlStyle-CssClass="button save" ShowEditButton="True">
<ControlStyle CssClass="button save" />
</asp:CommandField>
<asp:BoundField DataField="ProgramNumber" HeaderText="ProgramNumber"
InsertVisible="False" ReadOnly="True" SortExpression="ProgramNumber" />
<asp:BoundField DataField="ProgramName" HeaderText="ProgramName"
SortExpression="ProgramName" />
<asp:BoundField DataField="ProgramStatus" HeaderText="ProgramStatus"
SortExpression="ProgramStatus" />
<asp:BoundField DataField="RecordType" HeaderText="RecordType"
SortExpression="RecordType" />
<asp:BoundField DataField="ProgramInformation" HeaderText="ProgramInformation"
SortExpression="ProgramInformation" />
</Columns>
</asp:GridView>
</ContentTemplate>
default.aspx.vb
Imports System.Web.Services
Partial Class processes_ProgramTrack_Default
Public Property SortOrder() As String
Get
If (ViewState("SortOrder").ToString = "desc") Then
ViewState("SortOrder") = "asc;"
Else
ViewState("SortOrder") = "desc"
End If
Return ViewState("SortOrder").ToString()
End Get
Set(ByVal value As String)
ViewState("SortOrder") = value
End Set
End Property
Public Sub bindGridView(Optional ByVal sortExp As String = "", Optional ByVal sortDir As String = "")
Dim connstr As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As New SqlConnection(connstr)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim myDataView As New DataView()
Dim mysqlCommand As New SqlCommand("SELECT tblPrgTrackPrograms.ProgramNumber, tblPrgTrackPrograms.ProgramName, tblPrgTrackPrograms.ProgramStatus, tblPrgTrackProgramDocumentation.RecordType, tblPrgTrackProgramDocumentation.ProgramInformation FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber")
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(mysqlCommand)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
myDataView = myDataSet.Tables(0).DefaultView
If sortExp <> String.Empty Then
myDataView.Sort = String.Format("{0}{1}", sortExp, sortDir)
End If
gvProgramDetails.DataSource = myDataView
gvProgramDetails.DataBind()
End Sub
Protected Sub gvProgramDetails_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvProgramDetails.Load
bindGridView()
End Sub
Protected Sub gvProgramDetails_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvProgramDetails.PageIndexChanging
gvProgramDetails.PageIndex = e.NewPageIndex
bindGridView()
End Sub
Protected Sub gvProgramDetails_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvProgramDetails.RowDeleting
End Sub
Protected Sub gvProgramDetails_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProgramDetails.Sorting
SortOrder = ViewState("SortOrder").ToString
bindGridView(e.SortExpression, SortOrder)
End Sub
End Class
I get the error message as a popup msgbox. What I think is happening, SortOrder isn't getting assigned a value.
You need to make sure that you ViewState("SortOrder") has a value in it before you try to call ToString. Otherwise, it will throw that exception (as you've seen) because you cannot call the ToString method on null.
Essentially, you need to wrap your references to that ViewState variable in a "If (ViewState("SortOrder") IsNot Nothing Then" block, and possibly provide special handling in the "Else" section (if you need that).
Something like this for your property:
Public Property SortOrder() As String
Get
If (ViewState("SortOrder") IsNot Nothing Then
If (ViewState("SortOrder").ToString = "desc") Then
ViewState("SortOrder") = "asc;"
Else
ViewState("SortOrder") = "desc"
End If
End If
Return ViewState("SortOrder").ToString()
End Get
Set(ByVal value As String)
ViewState("SortOrder") = value
End Set
End Property
And then the same thing for your sorting event:
Protected Sub gvProgramDetails_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProgramDetails.Sorting
If (ViewState("SortOrder") IsNot Nothing Then
SortOrder = ViewState("SortOrder").ToString
bindGridView(e.SortExpression, SortOrder)
End If
End Sub
Note: This is my best guess at your problem, given the information you've provided so far. If you provide the line that's throwing the error, I'd be glad to take another look.
I have a GridView that has it's columns added dynamically in codebehind. I've added paging to the GridView, and it works, but when it goes to the next page, it adds the columns again.
So the GridView starts out with 2 columns (Last Name and First Name) added from codebehind. Then I go to it's next page, and it properly loads the next page of results, but now with 4 columns (Last Name, First Name, Last Name, First Name).
What am I doing wrong here?
Here's the code for the GridView:
<asp:GridView id="GridView3" runat="server" AutoGenerateColumns="False"
EmptyDataText="There are no data records to display."
AllowPaging="True"
OnPageIndexChanging="GridView3_PageIndexChanging"
CssClass="GridViewStyle" GridLines="None" Width="100%">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="EmplID"
DataNavigateUrlFormatString="EmployeeProfile.aspx?EmplID={0}"
DataTextField="EmplID"
DataTextFormatString= "<img src='Images/icons/document-search-result.png' alt='View'/> <u>View</u>" >
<ControlStyle CssClass="titleLinksB" />
<ItemStyle Wrap="False" />
</asp:HyperLinkField>
</Columns>
</asp:GridView>
Here's the code for the codebehind:
Private Sub loadDynamicGrid()
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim lastName As String
Dim linkText As String
lastName = Request.QueryString("lastName")
connetionString = ConfigurationManager.ConnectionStrings("dbConnectionString").ConnectionString.ToString()
sql = "SELECT * FROM [EmployeeList] Where [lastname] like '" & lastName & "%' order by lastname"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
Dim curLastName As New BoundField
curLastName.HeaderText = "Last Name"
curLastName.DataField = "LastName"
GridView3.Columns.Insert(0, curLastName)
Dim curFirstName As New BoundField
curFirstName.HeaderText = "First Name"
curFirstName.DataField = "FirstName"
GridView3.Columns.Insert(1, curFirstName)
GridView3.Visible = True
GridView3.DataSource = ds
GridView3.DataBind()
adapter.Dispose()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
And finally the Paging code:
Protected Sub GridView3_PageIndexChanging(ByVal sender As [Object], ByVal e As GridViewPageEventArgs)
GridView3.PageIndex = e.NewPageIndex
GridView3.DataBind()
End Sub
Any help is greatly appreciated!
I assume that you're calling loadDynamicGrid on every postback and not only If Not Page.IsPostBack.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
loadDynamicGrid()
End If
End Sub