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
Related
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:
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.
I have data I am trying to input into a gridview. I am looking up the number of rows for the gridview and adding data into them like this:
My "test" however does not get populated into the Submitted and Variance BoundFields in the Gridview. All that populates is the Company. Shouldn't "test" also populate in those other two columns?
Private Sub BindGrid()
Dim dt As New DataTable
dt.Columns.Add("Company")
dt.Columns.Add("Submitted")
dt.Columns.Add("Variance")
gvTally.DataSource = dt
Dim da As SqlClient.SqlDataAdapter
Dim strSQL2 As String
Dim Response As String = ""
strSQL2 = "SELECT [Company] FROM [Monetra].[dbo].[tbl_MonetraLogins]"
da = New SqlClient.SqlDataAdapter(strSQL2, System.Configuration.ConfigurationManager.AppSettings("MainConnectionString").ToString)
da.Fill(dt)
Dim dr As DataRow
For i As Integer = 0 To gvTally.Rows.Count - 1
dr = dt.NewRow
dr.Item("Company") = dt.Rows(i).Item("Company")
dr.Item("Submitted") = "test"
dr.Item("Variance") = "test"
dt.Rows.Add(dr)
Next
gvTally.DataSource = dt
gvTally.DataBind()
End Sub
Here is my ASP Grid:
<asp:GridView ID="gvTally" runat="server" EnableModelValidation="True"
AllowSorting="True" class="table table-condensed table-striped table-bordered table-hover no-margin" AutoGenerateColumns="False" Font-Size="Small">
<Columns>
<asp:BoundField DataField="Company" HeaderText="Company" >
<ItemStyle Width="180px" />
</asp:BoundField>
<asp:BoundField DataField="Submitted" HeaderText="Submitted" />
<asp:BoundField DataField="Variance" HeaderText="Variance" />
<asp:TemplateField HeaderText="Action" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CssClass="btn btn-success btn-small hidden-phone" Text="View" CommandName="View" />
</ItemTemplate>
<ItemStyle Width="60px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Try this vb code behind, then comment out my test
Private Sub BindGrid()
Dim dt_SQL_Results As New DataTable
'' Commenting out to use test data as I have no access to your database
'Dim da As SqlClient.SqlDataAdapter
'Dim strSQL2 As String
'Dim Response As String = ""
'strSQL2 = "SELECT [Company] FROM [Monetra].[dbo].[tbl_MonetraLogins]"
'da = New SqlClient.SqlDataAdapter(strSQL2, System.Configuration.ConfigurationManager.AppSettings("MainConnectionString").ToString)
'da.Fill(dt_SQL_Results)
'' Commenting out to use test data as I have no access to your database
'' Comment this block out after you test and uncomment the above code block
dt_SQL_Results.Columns.Add("Company")
Dim dr_SQL_Results As DataRow
For i As Integer = 0 To 5
dr_SQL_Results = dt_SQL_Results.NewRow
dr_SQL_Results.Item("Company") = "Company " & i
dt_SQL_Results.Rows.Add(dr_SQL_Results)
Next
'gvTally.DataSource = dt_SQL_Results
'gvTally.DataBind()
'' Comment this block out after you test and uncomment the above code block
Dim dt As New DataTable
dt.Columns.Add("Company")
dt.Columns.Add("Submitted")
dt.Columns.Add("Variance")
Dim dr As DataRow
For i As Integer = 0 To dt_SQL_Results.Rows.Count - 1
dr = dt.NewRow
dr.Item("Company") = dt_SQL_Results.Rows(i).Item("Company")
dr.Item("Submitted") = "test"
dr.Item("Variance") = "test"
dt.Rows.Add(dr)
Next
gvTally.DataSource = dt
gvTally.DataBind()
End Sub
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! :)
I have my GridView populating like so:
<asp:Panel ID="pnlGrid" runat="server">
<div class="m_container" style="margin-bottom:20px;">
<asp:GridView ID="grdView" runat="server" CssClass="GridViewStyle"
AutoGenerateColumns="False" GridLines="None" Width="125%" onrowdatabound="builderGridView_RowDataBound" >
<Columns>
<asp:BoundField DataField="id" Visible="False" />
<asp:BoundField HeaderText="Info" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton name='<%#Eval("status") %>' CommandArgument='<%#Eval("id")%>' runat="server" Text='<%#Eval("status")%>' CommandName='<%#Eval("status")%>' ID="statusLink" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle CssClass="RowS" />
<EmptyDataRowStyle CssClass="EmptyS" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedS" />
<HeaderStyle CssClass="HeaderS" />
<EditRowStyle CssClass="EditRowS" />
<AlternatingRowStyle CssClass="AltRowS" />
</asp:GridView>
</div>
</asp:Panel>
</asp:Content>
And the code behind is:
Private Sub LoadData(ByRef theStatus As Integer)
Dim objConn As MySqlConnection
Dim objCmd As MySqlCommand
objConn = New MySqlConnection(strConnString)
objConn.Open()
Dim strSQL As String
strSQL = "SELECT * FROM theTable WHERE status=" & theStatus & " ORDER BY created_on, status DESC;"
Dim dtReader As MySqlDataReader
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
grdView.DataSource = dtReader
grdView.DataBind()
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
End Sub
Then after the above i create a LinkButton for each row like so:
Sub builderGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lbtn As LinkButton = DirectCast(e.Row.FindControl("statusLink"), LinkButton)
e.Row.Cells(1).Text = "TEST!"
If lbtn.Text = 0 Then
Dim lb As New LinkButton()
lb.Text = "Accept"
lb.CommandName = lbtn.CommandName
lb.CommandArgument = lbtn.CommandArgument
lb.Attributes.Add("class", "nounderline")
lb.ForeColor = System.Drawing.Color.Green
lb.Font.Bold = True
lb.Font.Size = 12
lb.OnClientClick = "location.href = '/page.aspx?ID=" & pageID & "&dbid=" & lb.CommandArgument & "&ACCEPT=yes'; return false;"
e.Row.Cells(4).Controls.Add(lb)
End If
End If
End Sub
How can i get values from the database (name, address, email address, etc etc) and place it within the current row its going through?
example:
(when its looping through the rows)
e.Row.Cells(1).Text = database("FName") & "<BR />" & database("LName") & "<BR />"...etc etc
Would look like this in the first row column:
Bob
Barker
How can i grab whats currently being read from the DB?
builderGridView_RowDataBound event fill be handled for each row from the database.
e.Row.DataItem will contain the item from the database
Edit:
Better way would be
Using adap As New MySqlDataAdapter(objCmd)
Dim table As New DataTable()
adap.Fill(table)
grdView.DataSource = table;
grdview.DataBind();
Adapter will load all records to the DataTable.
Then your e.Row.DataItem will be of type DataRow