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

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.

Related

How to verify all button in approved in gridview while click on other button that is outside the gridview

I want to add one button in vb.net e.g bulk approval outside the gridview in another table. While clicking on that button I.e is bulk approval.. all verify button are verified in gridview in every row... and changed into verified.
Ok, so we have some kind of grid, and some kind of approve button for each row.
Ok, so we have some typical markup like this:
This is a grid (hotel bookings), and then a the "administrator" has to approve each one.
So, say some markup like this - nothing special:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="180" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Approved" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkApproved" runat="server" Checked='<%# Eval("Approved") %>'
CssClass="bigcheck" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="By">
<ItemTemplate>
<asp:Label ID="lblApBy" runat="server" Text='<%# Eval("ApprovedBy") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Approve">
<ItemTemplate>
<asp:Button ID="cmdApprove" runat="server" Text="Approve" CssClass="btn"
onclick="cmdApprove_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div style="float:right">
<asp:Button ID="cmdApproveAll" runat="server" Text="Approve All" CssClass="btn" />
And our code to load the grid:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT TOP 6 * from tblHotels"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
And we now have this:
Ok, so we have a plane jane button on each row. The code to approve a row is this code:
(a simple standard button in the grid view - button click)
Protected Sub cmdApprove_Click(sender As Object, e As EventArgs)
' approve one row
Dim btn As Button = sender
Dim gRow As GridViewRow = btn.NamingContainer
Call ApproveGRow(gRow)
End Sub
Sub ApproveGRow(gRow As GridViewRow)
' set checkbox = checked
Dim ckApprove As CheckBox = gRow.FindControl("chkApproved")
ckApprove.Checked = True
Dim lBy As Label = gRow.FindControl("lblApBy")
lBy.Text = UserInitials
' Get data base pk id
Dim pkID As Integer
pkID = GridView1.DataKeys(gRow.RowIndex).Item("ID")
' Now udpate database
Dim strSQL As String =
"UPDATE tblHotels SET Approved = 1, ApprovedBy = #Initials WHERE ID = #ID"
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#Initials", SqlDbType.NVarChar).Value = UserInitials
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = pkID
cmdSQL.ExecuteNonQuery()
End Using
End Using
End Sub
So, on a button click, we get the current row click, and then call our approve routine that accepts grid ro
So, if I click say on the second row, we see this:
However, what about do the WHOLE gird, with one button, and approve all rows?
Well, the button for the approve all looks like this:
Protected Sub cmdApproveAll_Click(sender As Object, e As EventArgs) Handles cmdApproveAll.Click
For Each gRow In GridView1.Rows
Call ApproveGRow(gRow)
Next
End Sub
And if I click on it, then I get this:

.NET - SelectedRow not returning any value

I am new with .net!
I have two gridviews connected to a large database. The first one is returning a list of issues searched by ID while the other is returning the issues searched by subject.
I am trying to get the ID from the gridview returning issues from a select button but when I use selectedRow it doesn't return anything.
I tried multiple methods and this is what I have now. Any Suggestions?
Protected Sub IssuesGV_SelectedIndexChanging(ByVal sender As Object, ByVal e As GridViewSelectEventArgs)
Dim pName As String
pName = IssuesGV.SelectedRow.Cells(0).Text
BindGridComments(pName)
End Sub
Protected Sub IssuesGV_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("onmouseover") = "this.style.backgroundColor='aquamarine';"
e.Row.Attributes("onmouseout") = "this.style.backgroundColor='white';"
e.Row.ToolTip = "Click last column for selecting this row."
' e.Row.Cells(0).Attributes.Add("onclick", )
End If
End Sub
Protected Sub IssuesGV_RowCommand(sender As Object, e As GridViewCommandEventArgs)
' ' Dim row As GridViewRow = IssuesGV.Rows(rowIndex)
' v = row.Cells(1).Text
'v = IssuesGV.SelectedRow.Cells(0).Text
' TextBox1.Text = v
'TextBox1.Text = v
If (e.CommandName = "Select1") Then
Dim index As Int16
index = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow
row = IssuesGV.Rows(index)
Dim item As ListItem
item.Text = Server.HtmlDecode(row.Cells(0).Text)
End If
End Sub
My gridview code is the following (the one where I am using the select button):
<asp:GridView ID="IssuesGV" runat="server" AutoPostBack="true" OnRowCommand ="IssuesGV_RowCommand" OnRowDataBound="IssuesGV_RowDataBound" OnSelectedIndexChanged = "IssuesGV_OnSelectedIndexChanged" SelectedIndexChaning ="IssuesGV_SelectedIndexChanging" AutoGenerateColumns="False" DataKeyNames="number" DataSourceID="IssueDS" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="number" HeaderText="number" ReadOnly="True" SortExpression="number" />
<asp:BoundField DataField="subject" HeaderText="subject" SortExpression="subject" />
<asp:BoundField DataField="description" HeaderText="description" SortExpression="description" />
<asp:BoundField DataField="created_at" HeaderText="created_at" SortExpression="created_at" />
<asp:BoundField DataField="opener_name" HeaderText="opener_name" SortExpression="opener_name" />
<asp:BoundField DataField="project_name" HeaderText="project_name" SortExpression="project_name" />
<asp:ButtonField Text="Select" CommandName="Select1" ItemStyle-Width="30" ButtonType="Button" HeaderText="Select" ShowHeader="True" SortExpression="number" >
<ItemStyle Width="30px" />
</asp:ButtonField>
</Columns>
</asp:GridView>
The error I am receiving is this one:
System.ArgumentOutOfRangeException HResult=0x80131502
Message=Index was out of range. Must be non-negative and less than the
size of the collection. Parameter name: index Source= StackTrace:
Many Thanks!
Front End:
Your GridView should look like this:
<asp:GridView ID="IssuesGV" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="IssuesGV_OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="number" HeaderText="number" />
...Some Other Fields
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
Back End:
Then add this code OnSelectedIndexChanged of GridView:
Protected Sub IssuesGV_OnSelectedIndexChanged(sender As Object, e As EventArgs)
'Accessing Selected BoundField Column
Dim number As String = IssuesGV.SelectedRow.Cells(0).Text
label.Text = "<b>Number Value:</b> " & number & " <b>"
End Sub
Ref: See full example here.
Edit
For some reason, if OnSelectedIndexChanged method is not firing then you've just need to add below attribute in your GridView header markup:
AutoGenerateSelectButton="True"
This will create a Select link in your GridView rows, which'll fire the OnSelectedIndexChanged method.
PS: If above all workarounds not works then see this post.

Dynamically update GridView results based on text entered into a textbox

I would like to dynamically update the results of a GridView based on characters that are entered into a textbox. My code currently works but only fires the update when the textbox loses focus or the user tabs out of the textbox. AutoPost is set to true for the textbox. I have the code to refresh the SQLDataSource, I just want the update to happen as the user enters characters in the textbox. I imagine this will require client side action, but not sure where to start. Thank you.
MARKUP
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True" ViewStateMode="Enabled"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="NameFirst" HeaderText="First Name" SortExpression="NameFirst" />
<asp:BoundField DataField="NameLast" HeaderText="Last Name" SortExpression="NameLast" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="State_ID" HeaderText="State" SortExpression="State_ID" />
</Columns>
</asp:GridView>
CODEBEHIND
Protected Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
GridData()
End Sub
Private Sub GridData()
Dim conString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ToString()
Dim sqlcon As New SqlConnection(conString)
Dim sqlcmd As SqlCommand
Dim da As SqlDataAdapter
Dim dt As New System.Data.DataTable()
Dim query As [String]
If txtsearch.Text = "" Then
query = "SELECT [Individual_ID], [NameFirst], [NameLast], [Address], [City], [State_ID], [ZipCode], [Comment] FROM [t_Individual] ORDER BY [NameLast], [NameFirst]"
Else
query = "SELECT [Individual_ID], [NameFirst], [NameLast], [Address], [City], [State_ID], [ZipCode], [Comment] FROM [t_Individual] WHERE [NameLast] LIKE N'%" + txtSearch.Text + "%' ORDER BY [NameLast], [NameFirst]"
End If
sqlcmd = New SqlCommand(query, sqlcon)
sqlcon.Open()
da = New SqlDataAdapter(sqlcmd)
dt.Clear()
da.Fill(dt)
If dt.Rows.Count > 0 Then
GridView1.DataSourceID = ""
GridView1.DataSource = dt
GridView1.DataBind()
Else
GridView1.DataBind()
End If
sqlcon.Close()
End Sub

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! :)

why button click insert data twice

i have this button which i add in row of data however, i only add two row of the date, when click this button it give me 4 data, each date is being inserted twice meaning date A den date B den date A and den date B, what the problem
Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
Dim rowIndex As Integer = 0
Dim sc As New StringCollection()
Dim sc1 As New Date
If ViewState("CurrentTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count < 10 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
'extract the TextBox values
Dim box5 As TextBox = DirectCast(Gridview3.Rows(rowIndex).Cells(1).FindControl("TextBox5"), TextBox)
Dim box7 As Date = Convert.ToDateTime(box5.Text)
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("mydatabase").ConnectionString
Dim cmd As String
cmd = "Insert into Date values (#date) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
myCmd.Parameters.Add(New SqlParameter("#date", box7))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
rowIndex += 1
Next
End If
Else
' lblMessage.Text = "Cannot save as there no information recorded"
MsgBox("failed")
End If
End Sub
<asp:GridView ID="Gridview3" runat="server" AutoGenerateColumns="False"
Height="89px" ShowFooter="True" Width="303px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="No of Available:" />
<asp:TemplateField HeaderText="New Date Available :">
<ItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" />
<AjaxToolkit:CalendarExtender ID="calExtender6" runat="server"
Format="dd/MM/yyyy" OnClientDateSelectionChanged="CheckDateEalier"
TargetControlID="TextBox5" />
</ItemTemplate>
<FooterStyle Height="22px" HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" onclick="ButtonAdd_Click"
Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView> 
Protected Sub ButtonAdd_Click(sender As Object, e As System.EventArgs)
AddNewRowToGrid()
End Sub
You called the function twice, once when you declare "Handles Button2.Click" and second when you set the onclick="ButtonAdd_Click".
You need to choose one of the options.
Hope that's help
Please check in the view page. I have experienced a similar issue like this in my struts,spring,hibernate application. My action method was called twice. This is because i have give the tag for the button as submit. something like <button:submit... . Just ensure that your method is called once or twice.
I had a similar problem, I created another button and copied all codes of the first button and inserted behind the new button, now the problem has solved.
it worked for me.

Resources