Gridview sorting up/down arrow in column headers - asp.net

I'm currently working on some code which is taking care of sorting and paging data in a gridview. I'm now trying to implement sorting arrow (up/down arrows next to column headers) but I have no success. The code to implement the sorting arrows is located in the *GridView1_RowCreated* sub routine. Right now, when I run the code, I don't see the sorting arrows at all. The problematic line is the following one: "If tblAdministrators.SortExpression = lnk.CommandArgument Then" I can't figure out what's wrong with that line. It's always False therefore the arrows don't show up.
Private Function GetData(sort As SortDirection) As Data.DataView
Dim connection As OracleDBConnect = DAL.GetOracleDBConnection()
Dim request As OracleDBRequest = Nothing
Dim result As OracleDBResult = Nothing
Dim trace As OracleDBChronoTrace = Nothing
Dim status As DBStatus
Dim sb As New StringBuilder
Dim dv As DataView
With sb
.Append("SELECT * FROM USERS")
End With
request = New OracleDBRequest(sb.ToString, CommandType.Text)
status = connection.Execute(request, result, trace)
dv = New DataView(result.DataSet.Tables(0))
If (ViewState("sortExp") IsNot Nothing) Then
dv = New Data.DataView(result.DataSet.Tables(0))
If (GridViewSortDirection = SortDirection.Ascending) Then
GridViewSortDirection = SortDirection.Descending
dv.Sort = CType(ViewState("sortExp").ToString() & DESCENDING, String)
Else
GridViewSortDirection = SortDirection.Ascending
dv.Sort = CType(ViewState("sortExp").ToString() & ASCENDING, String)
End If
Else
dv = result.DataSet.Tables(0).DefaultView
End If
Return dv
End Function
Public Property GridViewSortDirection() As SortDirection
Get
If ViewState("sortDir") Is Nothing Then
ViewState("sortDir") = SortDirection.Ascending
End If
Return CType(ViewState("sortDir"), SortDirection)
End Get
Set(ByVal value As SortDirection)
ViewState("sortDir") = value
End Set
End Property
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles tblAdministrators.PageIndexChanging
tblAdministrators.PageIndex = e.NewPageIndex
GridViewSortDirection = If(GridViewSortDirection = SortDirection.Descending, SortDirection.Ascending, SortDirection.Descending)
tblAdministrators.DataSource = GetData(GridViewSortDirection)
tblAdministrators.DataBind()
End Sub
Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles tblAdministrators.Sorting
ViewState("sortExp") = e.SortExpression
tblAdministrators.DataSource = GetData(GridViewSortDirection)
tblAdministrators.DataBind()
End Sub
Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles tblAdministrators.RowCreated
If e.Row.RowType = DataControlRowType.Header Then
For Each tc As TableCell In e.Row.Cells
If tc.HasControls() Then
Dim lnk As LinkButton = DirectCast(tc.Controls(0), LinkButton)
If lnk IsNot Nothing Then
Dim img As New System.Web.UI.WebControls.Image()
img.ImageUrl = "/images/" & (If(GridViewSortDirection = SortDirection.Ascending, "asc", "desc")) & ".gif"
If tblAdministrators.SortExpression = lnk.CommandArgument Then
tc.Controls.Add(New LiteralControl(" "))
tc.Controls.Add(img)
End If
End If
End If
Next
End If
End Sub
ASPX code:
<asp:GridView ID="tblAdministrators" runat="server" AutoGenerateColumns="false" EmptyDataText="No records found" PageSize="25" AllowPaging="True" AllowSorting="True" OnRowCreated="GridView1_RowCreated">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" SortExpression="NAME"></asp:BoundField>
</Columns>
<Columns>
<asp:BoundField HeaderText="City" DataField="City" SortExpression="CITY"></asp:BoundField>
</Columns>
</asp:GridView>

Take a look at my sample:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerId"
DataSourceID="SqlDataSource1">
<SortedAscendingHeaderStyle CssClass="sortasc" />
<SortedDescendingHeaderStyle CssClass="sortdesc" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId"
InsertVisible="False" ReadOnly="True" SortExpression="CustomerId" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="IdNumber" HeaderText="IdNumber"
SortExpression="IdNumber" />
</Columns>
</asp:GridView>
Pay attention on SortedAscendingHeaderStyle and SortedDescendingHeaderStyle. Just create apropriate css classes with background image (arrow up and arrow down) and you are done.

In Order to add a sorting arrow in a Data Grid on a VB.net Windows Form, you don't even have to write any code
On form in Design Mode - select the grid you are working with, right click go to properties, set Selection Mode = Cell Select
On form in Design Mode - click the arrow on the grid on the right up, to edit column properties, select edit or add columns, set SortMode = Automatic
If you have code for your cell content (say you want user to open another form while clicking on any row in the data grid) then use CellDoubleClick property to handle the event. If the you have used single click then it will sort the header and also open the form for the given cell
Private Sub _CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGAcctGrpList.CellDoubleClick

Related

Add (insert) new row textbox in grid view programmatically not showing

so I have this code for grid view in asp.net
<asp:GridView ID="grdNewClaim" CssClass="table table-bordered table-condensed" GridLines="None" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="claim_type" HeaderText="Claim Type" />
<asp:BoundField DataField="purpose_desc" HeaderText="Purpos/Description" />
<asp:BoundField DataField="currency" HeaderText="Currency" />
<asp:BoundField DataField="amount" HeaderText="Amount" />
<asp:TemplateField HeaderText="Currency Rate">
<ItemTemplate>
<asp:TextBox ID="txtChangeCurrRate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Converted Rate">
<ItemTemplate>
<asp:TextBox ID="txtChangeConvertedRate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And this code to add the new row for the gridview
Private Sub addClaimProgrammatically()
Dim dt As New DataTable
Dim dr As DataRow
If grdNewClaim.Rows.Count = 0 Then
dt.Columns.Add("claim_type")
dt.Columns.Add("purpose_desc")
dt.Columns.Add("currency")
dt.Columns.Add("amount")
dt.Columns.Add("txtChangeCurrRate")
dt.Columns.Add("txtChangeConvertedRate")
dr = dt.NewRow
dr.Item("claim_type") = cmbClaimtype.Text
dr.Item("purpose_desc") = txtPurpDesc.Text
dr.Item("currency") = cmbCurrency.Value
dr.Item("amount") = txtAmmount.Text
dr.Item("txtChangeCurrRate") = lblCurrencyrate.Text
dr.Item("txtChangeConvertedRate") = lblconvertedRateMYR.Text
dt.Rows.Add(dr)
End If
grdNewClaim.DataSource = dt
grdNewClaim.DataBind()
End Sub
But for some reason the items for for both textbox just blank like this :
So any idea why? Because if I change the textbox to <asp:BoundField/> it works just fine like this
[![enter image description here][2]][2]
EDIT : create another rows in gridview
My markup is exactly the same as you. So this is my code behind. This code works just fine, however the only problem is my textbox for first row went blank. The second row is alright.
NOTE : I didn't do this on page_load.
Private Sub LoadGrid()
grdNewClaim.DataSource = dtGrd
grdNewClaim.DataBind()
End Sub
Private Sub addClaimProgrammatically()
Dim dr As DataRow
If grdNewClaim.Rows.Count = 0 Then
dtGrd.Columns.Add("claim_type")
dtGrd.Columns.Add("purpose_desc")
dtGrd.Columns.Add("currency")
dtGrd.Columns.Add("amount")
dtGrd.Columns.Add("CurrencyRate")
dtGrd.Columns.Add("ConvertedRate")
dr = dtGrd.NewRow
dr.Item("claim_type") = cmbClaimtype.Text
dr.Item("purpose_desc") = txtPurpDesc.Text
dr.Item("currency") = cmbCurrency.Value
dr.Item("amount") = txtAmmount.Text
dr.Item("CurrencyRate") = lblCurrencyrate.Text
dr.Item("ConvertedRate") = lblconvertedRateMYR.Text
dtGrd.Rows.Add(dr)
ElseIf grdNewClaim.Rows.Count > 0 Then
dtGrd.Columns.Add("claim_type")
dtGrd.Columns.Add("purpose_desc")
dtGrd.Columns.Add("currency")
dtGrd.Columns.Add("amount")
dtGrd.Columns.Add("CurrencyRate")
dtGrd.Columns.Add("ConvertedRate")
For i = 0 To grdNewClaim.Rows.Count - 1
dr = dtGrd.NewRow
dr.Item("claim_type") = grdNewClaim.Rows(i).Cells(1).Text
dr.Item("purpose_desc") = grdNewClaim.Rows(i).Cells(2).Text
dr.Item("currency") = grdNewClaim.Rows(i).Cells(3).Text
dr.Item("amount") = grdNewClaim.Rows(i).Cells(4).Text
dr.Item("CurrencyRate") = grdNewClaim.Rows(i).Cells(5).Text
dr.Item("ConvertedRate") = grdNewClaim.Rows(i).Cells(6).Text
dtGrd.Rows.Add(dr)
Next
dr = dtGrd.NewRow
dr.Item("claim_type") = cmbClaimtype.Text
dr.Item("purpose_desc") = txtPurpDesc.Text
dr.Item("currency") = cmbCurrency.Value
dr.Item("amount") = txtAmmount.Text
dr.Item("CurrencyRate") = lblCurrencyrate.Text
dr.Item("ConvertedRate") = lblconvertedRateMYR.Text
dtGrd.Rows.Add(dr)
End If
LoadGrid()
End Sub
Protected Sub btnAddClaim_Click(sender As Object, e As EventArgs) Handles btnAddClaim.Click
addClaimProgrammatically()
End Sub
The values just went missing
Thank you very much for your time !
When you use a boundfield, it works because you CAN SPECIFY which column to display.
bound field only works due to this:
Computers do not "guess" or "assume" what data column to use here.
But, when you use a templated column, and a standard control, then you need to use a expression that defines which column to use.
eg this:
<asp:TemplateField HeaderText="Currency Rate">
<ItemTemplate>
<asp:TextBox ID="txtChangeCurrRate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
so, in above, ask this question:
Where in above does the markup KNOW which column to use?
So, you have to use a binding expression, since TextBox does not have a "boundfield" property to tell it which column to use.
Try like this:
<asp:TemplateField HeaderText="Currency Rate">
<ItemTemplate>
<asp:TextBox ID="txtChangeCurrRate" runat="server"
Text = '<%# Eval("Currency") %>'
></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
So, in above, we would be using column "Currency" for the text (or you can use "amount" or "purpose_desc" or any column from the data source.
So, your example does not work, since with a templated textbox, you have to specify the column to use - (by some how and some way). So, use the above binding expression.
Edit: data does not persist - only can add one row.
Correct - you need to save that table between each post-back, and NOT re-create the table from scratch each time, else you lose previous rows.
So, the code has to look like this:
NOTE how I defined dt at the class level (right before page load).
And note how I "restore" this dt in page load EACH time.
So, your code will become this
Markup like this:
<asp:GridView ID="grdNewClaim" CssClass="table table-bordered table-condensed"
GridLines="None" runat="server" AutoGenerateColumns="false"
ShowHeaderWhenEmpty="true" >
<Columns>
<asp:BoundField DataField="claim_type" HeaderText="Claim Type" />
<asp:BoundField DataField="purpose_desc" HeaderText="Purpos/Description" />
<asp:BoundField DataField="currency" HeaderText="Currency" />
<asp:BoundField DataField="amount" HeaderText="Amount" />
<asp:TemplateField HeaderText="Currency Rate">
<ItemTemplate>
<asp:TextBox ID="txtCRateZoo" runat="server"
Text = '<%# Eval("txtChangeCurrRate") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Converted Rate">
<ItemTemplate>
<asp:TextBox ID="txtConvertedRate" runat="server"
Text = '<%# Eval("txtChangeCurrRate") %>' >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And code now like this:
Dim dt As New DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
CreateTable()
LoadGrid()
Session("dt") = dt
Else
' restore table
dt = Session("dt")
End If
End Sub
Sub CreateTable()
dt.Columns.Add("claim_type", GetType(String))
dt.Columns.Add("purpose_desc")
dt.Columns.Add("currency", GetType(Double))
dt.Columns.Add("amount", GetType(Double))
dt.Columns.Add("txtChangeCurrRate", GetType(Double))
dt.Columns.Add("txtChangeConvertedRate", GetType(Double))
End Sub
Sub LoadGrid()
grdNewClaim.DataSource = dt
grdNewClaim.DataBind()
End Sub
Private Sub addClaimProgrammatically()
Dim dr As DataRow
dr = dt.NewRow
dr.Item("claim_type") = cmbClaimtype.Text
dr.Item("purpose_desc") = txtPurpDesc.Text
dr.Item("currency") = cmbCurrency.Value
dr.Item("amount") = txtAmmount.Text
dr.Item("txtChangeCurrRate") = lblCurrencyrate.Text
dr.Item("txtChangeConvertedRate") = lblconvertedRateMYR.Text
dt.Rows.Add(dr)
LoadGrid()
End Sub
Edit2: allow edits of two text box - save back to table.
So, just add this to the code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
CreateTable()
LoadGrid()
Session("dt") = dt
Else
' restore table
dt = Session("dt")
' restore grid to dt
GridToTable
End If
End Sub
Sub GridToTable()
' move any and all possile updates to grid back to our table dt
For Each gRow As GridViewRow In grdNewClaim.Rows
Dim OneRow As DataRow = dt.Rows(gRow.RowIndex)
Dim txtCurrRate As TextBox = gRow.FindControl("txtCRateZoo")
Dim txtConvertRate As TextBox = gRow.FindControl("txtConvertedRate")
OneRow("txtChangeCurrRate") = txtCurrRate.Text
OneRow("txtChangeConvertedRate") = txtConvertRate.Text
Next
End Sub
What we do is send any changes back to the dt.
This means, that any button click etc on that page will shuffle gv back to dt.
This also means that if you have a button click to jump or move on to the next page/url, then session("dt") will have the correct data.
but, since we doing this on page load, then don't use a link button, or a button with post-back url to jump to the next page (just use regular button + code behind, and say:
Response.Redirect("url to next page to jump to")
So, with above, user can now freely modify the two columns, and they will be sent back to the dt.
This also means you can loop/process the dt in code.
Say we drop a button on the form, and then behind that button we do this:
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each OneRow As DataRow In dt.Rows
Debug.Print(OneRow("currency"))
Debug.Print(OneRow("txtChangeCurrRate"))
' etc . etc.
Next
End Sub
So, we don't even have to hit the original grid, and our dt will be always updated in our session(). So, we now can work with table in code - not have to use the grid. As such, then we could have a button "continue" to move on to the next page - as along as we follow above setup, then dt will always have the latest data and edits upon a post-back.

Check Row when changing pages in GridView

When clicking the pager in a GridView, I want to highlight each row if the amount equals a certain amount. I have this working when the GridView is first populated, but each time I click the pager button to move to the next page with a valid amount, it will not highlight. Any suggestions?
GridView
<asp:GridView ID="ERNDataGrid" runat="server" CssClass="clsGridView" AutoGenerateColumns="false" AllowPaging="true" PageSize="15"
OnPageIndexChanging="OnPageIndexChanging" OnRowDataBound="OnRowDataBound" Width="99%">
<HeaderStyle HorizontalAlign="Center" BackColor="#464646" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerSettings Mode="NextPreviousFirstLast" />
<PagerStyle HorizontalAlign="Right" ForeColor="White" BackColor="#464646" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False"></PagerStyle>
<AlternatingRowStyle BackColor="#DDDDDD"></AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="CUID" HeaderText="Routing Number" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Account" HeaderText="Account" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Amount" HeaderText="Amount" DataFormatString="{0:C}" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Serial" HeaderText="Check Number" ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
VB.net Codebehind
Protected Sub ResearchGridView_Click(sender As Object, e As EventArgs) Handles ResearchGridView.Click
strResearchAmount = txtERNResearchAmount.Value
BindData()
End Sub
Private Sub ERNResearch_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ERNDataGrid.DataBind()
End If
End Sub
Protected Sub BindData()
'Create a connection
Dim myConnection As New SqlConnection("This works")
'Create the command object, passing in the SQL string
Const strSQL As String = "SELECT CUID, Account, Amount / 100 as Amount, Serial FROM [ACCU].[dbo].[ERN_ITEM_VIEW] Where Date = '04/13/2017' And CUID <> '0'"
Dim myCommand As New SqlCommand(strSQL, myConnection)
'Create the DataAdapter
Dim myDA As New SqlDataAdapter()
myDA.SelectCommand = myCommand
'Populate the DataSet
Dim myDS As New DataSet()
myDA.Fill(myDS)
'Set the datagrid's datasource to the dataset and databind
ERNDataGrid.DataSource = myDS
ERNDataGrid.DataBind()
'Display Information on what page we are currently viewing
'lblMessage.Text = "Viewing Page " & ERNDataGrid.PageIndex + 1 & " of " & ERNDataGrid.PageCount
End Sub
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
ERNDataGrid.PageIndex = e.NewPageIndex
Me.BindData()
End Sub
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowIndex > -1 Then
If e.Row.Cells(2).Text = "$" & strResearchAmount Then
e.Row.BackColor = Color.Yellow
End If
End If
End Sub
Your code looks correct. The OnRowDataBound event is triggered every time DataBind() is called. And since that is the case in your OnPageIndexChanging the RowDataBound should fire.
However the strResearchAmount could be empty since it is filled only after a button click. Since a page index change also triggers a PostBack, it is likely that strResearchAmount is empty when OnRowDataBound is called for the second time.
Check the value of strResearchAmount and make sure it persists across PostBack.

copy row from asp.net gridview to new page using VB

I am trying to copy a row from a gridview to be displayed on a new page through a button in one of the columns in the gridview. I have my gridview populated from an Access database that is linked to my project. I have tried several different things, but nothing will display the row information when the project is ran. The current code I am trying from the actual dataview is:
Example 1a
<asp:GridView ID="Grid1" runat="server" Width ="90%" AutoGenerateColumns="false" OnRowDeleting="Grid1_RowDeleting" DataKeyNames="Title">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="Console" HeaderText="Console" />
<asp:BoundField DataField="Year_Released" HeaderText="Year Released" />
<asp:BoundField DataField="ESRB" HeaderText="ESRB Rating" />
<asp:BoundField DataField="Score" HeaderText="Personal Score" />
<asp:BoundField DataField="Publisher" HeaderText="Publisher" />
<asp:BoundField DataField="Developer" HeaderText="Developer" />
<asp:BoundField DataField="Genre" HeaderText="Genre" />
<asp:BoundField DataField="Purchase" HeaderText="Purchase Date" />
<asp:TemplateField ItemStyle-Width="7%" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" Text="View" PostBackUrl='<%# "~/ViewDetails.aspx?RowIndex=" & Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the codebehind code on the page where I am trying to have the code be displayed is:
Example 1b
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Me.Page.PreviousPage IsNot Nothing Then
Dim rowIndex As Integer = Integer.Parse(Request.QueryString("RowIndex"))
Dim GridView1 As GridView = DirectCast(Me.Page.PreviousPage.FindControl("Grid1"), GridView)
Dim row As GridViewRow = GridView1.Rows(rowIndex)
lblTitle.Text = row.Cells(0).Text
lblConsole.Text = row.Cells(1).Text
lblYear.Text = row.Cells(2).Text
lblESRB.Text = row.Cells(3).Text
lblScore.Text = row.Cells(4).Text
lblPublisher.Text = row.Cells(5).Text
lblDeveloper.Text = row.Cells(6).Text
lblGenre.Text = row.Cells(7).Text
lblPurchase.Text = row.Cells(8).Text
End If
End Sub
I have also tried another set of code where the button on the gridview was:
Example 2a
<asp:Button ID="btnLink" runat="server" Text="View Details" PostBackUrl='<%# Eval("Title", "~/ViewDetails.aspx?Id={0}") %>'/>
Where the codebehind code is:
Example 2b
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim GameTitle As String = Request.QueryString("Id")
Dim connString As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "DATA SOURCE=" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "App_Data" + "db1.accdb")
Using connection As New OleDbConnection(connString)
connection.Open()
Dim reader As OleDbDataReader = Nothing
Dim command As New OleDbCommand((Convert.ToString("SELECT * from [Video_Games] WHERE Title='") & GameTitle) + "'", connection)
reader = command.ExecuteReader()
While reader.Read()
lblTitle.Text = reader(0).ToString()
lblConsole.Text = reader(1).ToString()
lblYear.Text = reader(2).ToString()
lblESRB.Text = reader(3).ToString()
lblScore.Text = reader(4).ToString()
lblPublisher.Text = reader(5).ToString()
lblDeveloper.Text = reader(6).ToString()
lblGenre.Text = reader(7).ToString()
lblPurchase.Text = Convert.ToDateTime(reader(8).ToString()).ToShortDateString()
End While
End Using
End If
End Sub
End Class
I have tried making variations of both, mainly the second, but whatever I try the labels are not populated with the row information. Any assistance would be appreciated, and I can post any other code needed, like how I populated the gridview. Thank you.
It was as simple as changing the AutoEventWireup to "true" in my .aspx file.

How to get data from one page (databound) to another page's textbox in asp.net

Suppose I have two .aspx pages and a connection the the sql server database engine.
The first page, let's call it playground.aspx, I'm having a set of databound which using the stored procedure for SELECT function (using dataset for it).
Now in the second page, let's call it link.aspx, there are two textbox, suppose there are multiple data in the playground.aspx page and I want to retrieve Entity Code and Username data (from the playground.aspx's databound) and show it in the link.aspx's textbox.
How can I do that?
I was told to create some function, but I never dealt with a databound before, only with TextBox and Label, it really confused me.
Any help's appreciated, thank you.
EDIT (Here's the databound code)
<asp:Panel ID="PanelDGV" runat="server" Height="100%" ScrollBars="None" Width="100%">
<asp:GridView ID="DGV" runat="server" AutoGenerateColumns="False" GridLines="None"
AllowPaging="true" PageSize="2" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="EntityCode" HeaderText="Entity Code" />
<asp:BoundField DataField="UserName" HeaderText="Username" />
<asp:BoundField DataField="DivCode" HeaderText="Div Code" />
<asp:BoundField DataField="GroupCode" HeaderText="Group Code" />
<asp:BoundField DataField="CreatedBy" HeaderText="Created By" />
<asp:BoundField DataField="CreatedOn" HeaderText="Created On" />
<asp:BoundField DataField="ModifiedBy" HeaderText="Modified By" />
<asp:BoundField DataField="ModifiedOn" HeaderText="Modified On" />
<asp:ButtonField ButtonType="Image" ImageUrl="../Support/Image/Edit.png" ItemStyle-HorizontalAlign="Center"
CommandName="CmdEdit" HeaderText="Edit">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:ButtonField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</asp:Panel>
I just solved the problem, here's the code
For link.vb
Public Function F01_sysUser_Select(ByVal EntityCode As String, ByVal Username As String) As ProcessResult
Try
Dim SqlCmd As New SqlCommand()
SqlCmd.Connection = New SqlConnection(CF.CfgConnectionString)
SqlCmd.CommandType = CommandType.StoredProcedure
SqlCmd.CommandTimeout = CF.CfgCommandTimeout
SqlCmd.CommandText = "sysUser_SelectByID"
SqlCmd.Parameters.Add("#EntityCode", SqlDbType.VarChar) : SqlCmd.Parameters(0).Value = EntityCode
SqlCmd.Connection.Open()
Dim Dr As SqlDataReader = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection)
F01_Dt_sysUser.Clear()
F01_Dt_sysUser.Load(Dr)
If F01_Dt_sysUser.Rows.Count > 0 Then
Dr.Close()
Dr = Nothing
SqlCmd.Dispose()
Return ProcessResult.SuccessWithResult
Else
Dr.Close()
Dr = Nothing
SqlCmd.Dispose()
Return ProcessResult.SuccessWithNoResult
End If
Catch ex As Exception
InsertErrorLog("PlaygroundLink.F01_sysUser_Select", ex.Message)
ExMessage = ex.Message
Return ProcessResult.Failed
End Try
End Function
and in the link.aspx.vb:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim QSEntityCode As String
Dim QSUserName As String
QSEntityCode = Request.QueryString("QSEC").ToString
QSUserName = Request.QueryString("QSUN").ToString
Dim Bl As New PlaygroundLink
If Bl.F01_sysUser_Select(QSEntityCode, QSUserName) = CF.ProcessResult.SuccessWithResult Then
TbEntityCode.Text = QSEntityCode
TbUsername.Text = QSUserName
Else
' LblMessage.Text = Bl.ExMessage
End If
End Sub
lastly in playground.aspx.vb:
Private Sub DGV_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles DGV.RowCommand
If e.CommandName = "CmdEdit" Then
Dim QSEntityCode As String
Dim QSUserName As String
Dim idx As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = DGV.Rows(idx)
QSEntityCode = row.Cells(0).Text
QSUserName = row.Cells(1).Text
Response.Redirect(RR.PlaygroundLink & "?QSEC=" & QSEntityCode & "&QSUN=" & QSUserName)
End If
End Sub
After that, I get what I want, displaying the result in the link.aspx textbox, cheers! :)

How to create a GridView from a class

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

Resources