I have a search button and two textboxes that function as a datetime picker. What can I do to show all the records in a specific date interval? I am new to programming.
<%# Page Title="Report" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Report.aspx.vb"
Inherits="Report" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns ="false">
<Columns>
<asp:BoundField HeaderText="Part Number" DataField="Part_Number" readonly="true" ></asp:BoundField>
<asp:BoundField HeaderText="Last Inventory" DataField="Last_Inv" readonly="true" ></asp:BoundField>
<asp:BoundField HeaderText="Last Quantity" DataField="Last_Qty" readonly="true" ></asp:BoundField>
<asp:BoundField HeaderText="Inventory Today" DataField="Today_Inv" readonly="true" ></asp:BoundField>
<asp:BoundField HeaderText="Today's Quantity" DataField="Today_Qty" readonly="true" ></asp:BoundField>
</Columns>
</asp:GridView>
<br />
<br />
<div class ="container" >
<div class="input-group class col-sm-3 col-md-6">
<asp:Button ID="btnSearch" runat="server" Text="Search" />
<asp:TextBox ID="txtbxSearch1" runat="server" TextMode ="Date" Width="205px"></asp:TextBox>
<asp:TextBox ID="txtbxSearch2" runat="server" TextMode ="Date" Width="205px"></asp:TextBox>
</div> <br /> <br />
</div>
<br />
<br />
Imports System.Data
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As DataSet = New DataSet
ds.Tables.Add(New DataTable)
ds.Tables(0).Columns.AddRange(New DataColumn() {New DataColumn("Id", GetType(System.Int32)), New DataColumn("Name", GetType(System.String)), New DataColumn("DOB", GetType(DateTime))})
ds.Tables(0).Rows.Add(1, "John Hammond", "12/12/1996")
ds.Tables(0).Rows.Add(2, "Mudassar Khan", "11/16/1995")
ds.Tables(0).Rows.Add(3, "Suzanne Mathews", "10/20/1997")
ds.Tables(0).Rows.Add(4, "Robert Schidner", "09/22/1991")
Dim dt2 As DataTable = New DataTable
dt2 = ds.Tables(0).Select.Where(() => { }, ((Convert.ToDateTime(p("DOB")) >= Convert.ToDateTime("12/12/1996")) _
AndAlso (Convert.ToDateTime(p("DOB")) >= Convert.ToDateTime("12/12/1996")))).CopyToDataTable
GridView1.DataSource = dt2
GridView1.DataBind
End Sub
Also, this link below should get you going in the right direction.
https://forums.asp.net/t/2041882.aspx?GridView+Filter+between+2+dates
Related
I need select row in gridview with a button hidden, but without postback because i need that stay on position clicked in gridview, this step i got it, but when i clicked on row capture index = 0, but when i click in button (no hidden in this time), capture correct index, how can I do this, thanks for your help or any idea.
my code is:
aspx:
<asp:UpdatePanel ID="UPGrvConfident" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="table-responsive" id="gridDentalNetworkContainer" style="overflow: auto; height: 207px; cursor: pointer; padding: 0px">
<asp:GridView ID="gridDentalNetwork" EnableViewState="true" AllowSorting="false" runat="server" GridLines="None" Width="100%"
EmptyDataText="No hay elementos a mostrar." AutoGenerateColumns="false" ClientIDMode="Static"
DataKeyNames="numero" ShowHeaderWhenEmpty="true" HeaderStyle-HorizontalAlign="Center" HeaderStyle-BackColor="Gainsboro" HeaderStyle-BorderWidth="2px" RowStyle-BackColor="White"
RowStyle-BorderColor="White" RowStyle-Font-Size="Smaller" RowStyle-Font-Bold="false" CellPadding="3" CellSpacing="0">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" CommandName="Delete" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Numero" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Nombre" HeaderText="Nombre" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Identificacion" HeaderText="Identificación" ItemStyle-Width="10%" HeaderStyle-Width="10%" />
<asp:BoundField DataField="Msg" HeaderText="Nombre">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="ApellidoPaterno" HeaderText="Primer Apellido" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="ApellidoMaterno" HeaderText="Segundo Apellido" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Contrato" HeaderText="Contrato" />
<asp:BoundField DataField="contratocanal" HeaderText="Contratante" ItemStyle-Width="242px" HeaderStyle-Width="242px">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Titular" HeaderText="Usuario Principal">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="NroDoc" HeaderText="nro_row" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="NroPariente" HeaderText="nro_pariente" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="NroPol" HeaderText="nro_pol" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" HeaderStyle-Width="5px" />
<asp:BoundField DataField="NroAseg" HeaderText="nro_aseg" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="TxtRed" HeaderText="fec_nac" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Plan" HeaderText="Plan">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="fec_alta" HeaderText="Fecha Ingreso" ItemStyle-Width="96px" HeaderStyle-Width="96px">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
<AlternatingRowStyle BackColor="#f2f2f2" />
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
aspx.vb (code behind)
RowdataBound
Protected Sub gridDentalNetwork_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles gridDentalNetwork.RowDataBound
'e.Row.Cells(0).Style("display") = "none"
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';"
e.Row.Attributes("onmouseout") = "this.style.textDecoration='none';"
Dim btnSelect As Button = TryCast(e.Row.FindControl("btnSelect"), Button)
btnSelect.CommandArgument = e.Row.RowIndex.ToString()
'e.Row.Attributes("onclick") = String.Format("document.getElementById('{0}').click();", btnSelect.ClientID)
e.Row.Attributes.Add("onclick", "document.getElementById('" & btnSelect.ClientID & "').value = '" & e.Row.RowIndex.ToString() & "'; alert(document.getElementById('" & btnSelect.ClientID & "').value); darClick();")
'e.Row.Attributes.Add("onclick", "var dato = document.getElementById('btnSelect').value; '<%Session['temp']='+ dato +';%>'; alert('<%=Session['temp']%>');")
'e.Row.Attributes("onclick") = String.Format("document.getElementById('{0}').click();", btnSelect.ClientID)
'e.Row.Attributes("onclick") = Page.ClientScript.GetPostBackClientHyperlink(gridDentalNetwork, "Select$" + e.Row.RowIndex.ToString())
'e.Row.Attributes.Add("onclick", String.Format("document.getElementById('{0}').click();", btnSelect.ClientID))
e.Row.ToolTip = "Clic para seleccionar"
End If
End Sub
Method: I am using RowDeleting for commandField.
Protected Sub gridDentalNetwork_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs) Handles gridDentalNetwork.RowDeleting
Dim ListBiored As List(Of MClienteSimple) = New List(Of MClienteSimple)
Dim grvfila As GridViewRow
Dim indexx As String = Session("index")
grvfila = gridDentalNetwork.Rows(e.RowIndex)
Dim lstClientesConf As New MClienteDentalNetwork
lstClientesConf = DirectCast(Session("ClientesConf"), List(Of MClienteDentalNetwork))(grvfila.DataItemIndex)
...etc..etc
End Sub
In the VB code below, I'm trying to set the Hyperlink hypNote's text as "Add Note" when text is null. However it is not working. As a test, I've even set the Hyperlink text as "Test" and tried:
If hypNote.text = "Test" Then
hypNote.text = "Add Note"
End If
But still it doesn't work. Here's my code..
<asp:Panel ID="pnlOrders" runat="server">
<asp:Image ID="LiveOrders" alt="Live Gif" runat="server" class="extrasButton" ImageUrl="~/files/images/liveOrders.gif" />
<asp:SqlDataSource ID="DSOrders" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT tblOrders.OrderID, tblOrders.stallmessage, tblOrders.price, tblAccounts.city, tblAccounts.postcode, tblOrders.phoneNo, tblOrders.tblNo, tblOrders.info, tblOrders.orderDate, tblOrders.orderStatus, tblOrders.type, tblOrders.timeFor, tblOrders.paid, tblOrders.tblNo
FROM tblOrders INNER JOIN tblAccounts ON tblOrders.accountID = tblAccounts.AccountID
WHERE tblOrders.orderStatus='Completed'
ORDER BY tblOrders.timeFor ASC">
</asp:SqlDataSource>
<asp:GridView ID="gdvOrders" width="100%" runat="server" style="font-size:1.5em" ShowHeaderWhenEmpty="True" EmptyDataText="No orders" AllowPaging="True" AutoGenerateColumns="False" CssClass="mGrid" DataKeyNames="orderID" DataSourceID="DSOrders" PageSize="20" AllowSorting="True">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField HeaderText="Order">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("stallMessage") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="price" HeaderText="Price" />
<asp:BoundField DataField="phoneNo" HeaderText="Phone No" />
<asp:TemplateField HeaderText="Address/Table No.">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("tblNo") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-ForeColor="Red" HeaderText="Note">
<ItemTemplate>
<asp:HyperLink ID="hypNote" style="Font-Size:20px; color:Red;" runat="server" NavigateUrl='<%# "~/editNote.aspx?note=" & Eval("info").ToString & "&orderID=" & Eval("orderID").ToString %>' ><%# Eval("info") %></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="type" HeaderText="Type" />
<asp:BoundField DataField="orderDate" DataFormatString="{0: H:mm:ss}" HeaderText="Order Time" SortExpression="orderDate" />
<asp:BoundField DataField="timeFor" DataFormatString="{0: H:mm:ss}" HeaderText="Time For" SortExpression="timeFor" />
<asp:BoundField DataField="paid" HeaderText="Paid" />
<asp:TemplateField ShowHeader="True">
<ItemTemplate>
<asp:ImageButton visible="true" ID="lnkSent" runat="server" CausesValidation="False"
onclientclick="return confirm('Mark As Sent?');"
ImageUrl="~/files/images/icons/sendIcon.png" onclick="lnkSent_Click"></asp:ImageButton>
<asp:HiddenField ID="hidnOrderID" runat="server" Value='<%# Eval("orderID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
Protected Sub gdvOrders_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gdvOrders.RowDataBound
For Each r As GridViewRow in gdvOrders.Rows
If r.RowType = DataControlRowType.DataRow Then
Dim hypNote As Hyperlink
hypNote = r.Cells(4).FindControl("hypNote")
If hypNote.text = "" Then
hypNote.text = "Add Note"
End If
End If
Next r
End Sub
Additionally, I wish to change the text color of the Hyperlink when "Add Note" is displayed.
I figured out my mistake. I changed this line to:
<asp:HyperLink ID="hypNote" style="Font-Size:20px; color:Red;" text='<%# Eval("info") %>' runat="server" NavigateUrl='<%# "~/editNote.aspx?note=" & Eval("info").ToString & "&orderID=" & Eval("orderID").ToString %>' ></asp:HyperLink>
I didn't have text= in there.
All worked fine then.
I have updatePanel, in which I am having tables as shown
<asp:UpdatePanel ID="DynCreated" EnableViewState="true" UpdateMode="Conditional"
runat="server">
<ContentTemplate >
<div style="display: none" enableviewstate="true">
<asp:TextBox ID="flgClear" EnableViewState="true" Text="" runat="server"></asp:TextBox>
<asp:TextBox ID="flgAdd" EnableViewState="true" Text="" runat="server"></asp:TextBox>
<asp:TextBox ID="txtList" EnableViewState="true" Text="|" runat="server"></asp:TextBox>
<asp:TextBox ID="txtDelete" EnableViewState="true" Text="|" runat="server"></asp:TextBox></div>
<asp:Table ID="tblGrid" CssClass="grid" CellPadding="0" CellSpacing="0"
Width="100%" EnableViewState="true" runat="server"> <asp:TableRow TableSection="TableHeader" ID="trHeader" CssClass="crid-header Datagrid-header"
runat="server" EnableViewState="true">
<asp:TableHeaderCell ID="hdrSequence" runat="server">
<asp:Label ID="lblSequence" Text="#" CssClass="cel" runat="server" />
</asp:TableHeaderCell>
<asp:TableHeaderCell ID="hdrHouseBill" runat="server">
<asp:Label ID="lblHouseBill" Text="HouseBill" CssClass="ceva-form-label" runat="server" />
</asp:TableHeaderCell>
<asp:TableHeaderCell ID="hdrFileNumber" runat="server">
<asp:Label ID="lblFileNumber" Text="FileNumbere" CssClass="ceva-form-label" runat="server" />
</asp:TableHeaderCell>
</asp:TableRow>
</asp:Table>
<br />
<br />
<div class="text-center">
<asp:Button ID="btnAddNewHB" CssClass="tn btn-dialog" Text="Add New Status"
OnClientClick="return ShowNewLeg();" runat="server" />
<asp:Button Text="Validate" CssClass="cen btn-dialog" runat="server" ID="btnValidate" />
<asp:Button ID="btnSave" CssClass="tn-dialog" Text="Save" OnClientClick="return Save()" Visible="false"
runat="server" />
<asp:Button ID="btnCancel" CssClass=" btn-dialog" OnClientClick="window.returnValue = 1; window.close(); return false;"
Text="Cancel" CausesValidation="false" runat="server" />
<asp:Button ID="btnClear" CssClass=tn btn-dialog" Text="Clear All" OnClientClick="return ClearTable();"
runat="server" />
<input type="hidden" id="hndtimeformat" runat="server" name="hndtimeformat" value="0"
style="display: none" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
From the back-end i am adding new Row to the tblGrid
For j As Integer = tblGrid.Rows.Count To maxRow
Dim newRow As TableRow= New TableRow()
newRow.Cells.Add(CreateNewLabel(tblGrid.Rows.Count, "SEQ",
tblGrid.Rows.Count, tblGrid.Rows.Count, "40px", bColor))
newRow.Cells.Add(CreateNewText(tblGrid.Rows.Count, "HB", "",
tblGrid.Rows.Count, "10px", "", 3, "none", False))
newRow.Cells.Add(CreateNewLabel(tblGrid.Rows.Count, "FN", "", tblGrid.Rows.Count, "60px", ""))
newRow.Cells.Add(CreateNewDD(tblGrid.Rows.Count, "ST", statusup, tblGrid.Rows.Count, "10px", "", 3, "none", True))
newRow.Cells.Add(CreateNewDT(tblGrid.Rows.Count, "datetime", "", tblGrid.Rows.Count, ""))
newRow.Cells.Add(CreateNewAC(tblGrid.Rows.Count, "LC", "", "", tblGrid.Rows.Count, "0.0", AutoCompletor.DisplayFieldType.Code, "", "", False))
newRow.Cells.Add(CreateNewText(tblGrid.Rows.Count, "SG", "", tblGrid.Rows.Count, "10px", "", 0, "none"))
newRow.Cells.Add(CreateNewCB(tblGrid.Rows.Count, "CB", "", tblGrid.Rows.Count, "5px", bColor))
newRow.Cells.Add(CreateNewText(tblGrid.Rows.Count, "Note", "", tblGrid.Rows.Count, "10px", "", 0, "none"))
newRow.Cells.Add(CreateNewLabel(tblGrid.Rows.Count, "Er", "", tblGrid.Rows.Count, "40px", bColor))
newRow.Cells.Add(CreateNewImage(tblGrid.Rows.Count, "btn", tblGrid.Rows.Count)) tblGrid.Rows.Add(newRow) Next j
I am getting data what ever i have before post back, after post back its not having any data which is present in the tabGrid.
Do I need to use ViewState or Session? is there any way i get the data?
Please advice !!
Put your data into a viewstate and get them after postback
You can use a ViewState variable if you need to use this data only during navigation inside this page. If you want keep alive data for the entire session better to use a Session variable, so you will not loose these rows also if you go in other pages.
Asp:Table isn't the right element to use if you want manage data, i suggest to try this solution (is only an example):
<asp:GridView runat="server" ID="tblGrid" CssClass="grid" CellPadding="0" CellSpacing="0">
<Columns >
<asp:TemplateField >
<HeaderTemplate >
<asp:Label ID="lblSequence" Text="#" CssClass="cel" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSequenceItem" Text="<%# Eval("col1") %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblHouseBill" Text="HouseBill" CssClass="ceva-form-label" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblHouseBillItem" Text="<%# Eval("col2") %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblFileNumber" Text="FileNumbere" CssClass="ceva-form-label" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblFileNumberItem" Text="<%# Eval("col3") %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and this for runtime data binding:
Creation of datatable
Dim dt As New Data.DataTable("rows")
Dim col1 As New Data.DataColumn("col1", GetType(String))
Dim col2 As New Data.DataColumn("col2", GetType(Integer))
Dim col3 As New Data.DataColumn("col3", GetType(String))
dt.Columns.Add(col1)
dt.Columns.Add(col2)
dt.Columns.Add(col3)
dt.Rows.Add ("test",1,"test") 'statement for row insert
ViewState("datasource") = dt
tblGrid.DataSource = dt
tblGrid.DataBind()
And binding in postback:
Dim dt As New Data.DataTable("rows")
If Not ViewState("datasource") Is Nothing Then dt = ViewState("datasource")
tblGrid.DataSource = dt
tblGrid.DataBind()
Built a simple page linked to a SQL data source with two drop down lists. I'm very new at ASP.NET so excuse my simple newbie errors. At least I'm learning. Anyway object is to have 2 drop down lists, select a last name, and a company name using the common Northwind Database. I'm using the empID and custID as sql parameters. I didn't want the page to load the grid initially so I hid that and also created a clear button. When i run the page it will pull the correct data but when I select a different last name the page pulls the original data. Can someone help me understand where my mistake is?
asp.net code:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header><h1>Welcome to my First SQL Data Source Page</h1></header>
<h3>Select a Value from both drop Down Lists to find the orders that employee made</h3>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="LastName" DataValueField="EmployeeID" BackColor="#00CCFF" Height="25px" Width="200px">
<asp:ListItem>--Select Last Name--</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [LastName], [EmployeeID] FROM [Employees]"></asp:SqlDataSource>
<br />
<br />
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource2" DataTextField="CompanyName" DataValueField="CustomerID" BackColor="#00CCFF" Height="25px" Width="200px">
<asp:ListItem>--Select Company Name--</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [CompanyName], [CustomerID] FROM [Customers]"></asp:SqlDataSource>
<br />
<br />
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT * FROM ORDERS
WHERE
EmployeeID = #P1
AND
CustomerID = #P2
">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="P1" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="DropDownList2" Name="P2" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="OrderID" DataSourceID="SqlDataSource3"
EmptyDataText="There were no orders by this employee">
<alternatingrowstyle backcolor="#0066FF"
forecolor="DarkBlue"
font-italic="true"/>
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID" InsertVisible="False" ReadOnly="True" SortExpression="OrderID" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" SortExpression="CustomerID" />
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" SortExpression="EmployeeID" />
<asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" />
<asp:BoundField DataField="RequiredDate" HeaderText="RequiredDate" SortExpression="RequiredDate" />
<asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate" SortExpression="ShippedDate" />
<asp:BoundField DataField="ShipVia" HeaderText="ShipVia" SortExpression="ShipVia" />
<asp:BoundField DataField="Freight" HeaderText="Freight" SortExpression="Freight" />
<asp:BoundField DataField="ShipName" HeaderText="ShipName" SortExpression="ShipName" />
<asp:BoundField DataField="ShipAddress" HeaderText="ShipAddress" SortExpression="ShipAddress" />
<asp:BoundField DataField="ShipCity" HeaderText="ShipCity" SortExpression="ShipCity" />
<asp:BoundField DataField="ShipRegion" HeaderText="ShipRegion" SortExpression="ShipRegion" />
<asp:BoundField DataField="ShipPostalCode" HeaderText="ShipPostalCode" SortExpression="ShipPostalCode" />
<asp:BoundField DataField="ShipCountry" HeaderText="ShipCountry" SortExpression="ShipCountry" />
</Columns>
<HeaderStyle BackColor="#0066FF" ForeColor="White" />
</asp:GridView>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Search" BackColor="#00CCFF" BorderStyle="Inset" EnableTheming="True" Height="30px" Width="150px" />
<br />
<br />
<br />
<asp:Button ID="Button2" runat="server" Text="Clear" BackColor="#00CCFF" BorderStyle="Inset" Height="30px" Width="150px" />
</div>
</form>
</body>
</html>
Visual Basic Code:
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
GridView1.Visible = False
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GridView1.Visible = True
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
GridView1.Visible = False
End Sub
End Class
Use the Page.IsPostBack method to check whether it is a fresh load or in response to user action. Hide only when loading the page first time.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack() Then GridView1.Visible = False
End Sub
I am trying to build a website and am running into a little trouble. My coding knowledge and savvy are armature at best,if you know a better way to do this than please by all means let me know.
On my Featured Bar page I have two gridviews set up. gvPicsRandomBar(For pictures only) and GVRandomBars(For Information only). Each has their own SQLDataSource. I have it set up to where GVRandomBars selects a "random" bar through the SQL TOP command. What I'm trying to do is get the gvPicsRandomBar to display a picture of the same "random" bar that is selected by GVRandomBars. Both gridviews are querying from the same table but with different SELECT statements as each gridview is concerned with different items in the same table row.
I thought I had somewhat accomplished this by reading the primary key from the GVRandomBars and placing that value in a Label(lblRandomBar) that I use as a control for gvPicsRandomBar to match up the correct pic to display in it's own gridview as they both query the same database, but I was wrong. Whenever I startup my website I get this error "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index". I'm just not sure where to place this code i.e. (Event) lblRandomBar.Text = GVRandomBars.DataKeys(0).Value.ToString() so that I will not get the above error.
Seperate problems if by miracle I get it to work
One problem I have is that it appears that the value of the primary key is not passed on to lblRandomBar.text. I assume this is because I do not know where to correctly place the code lblRandomBar.Text = GVRandomBars.DataKeys(0).Value.ToString()The other problem I do have when I sometimes get it to work is that the picture displayed in gvPicsRandomBar is one step behind from when I click the search button. Example, I click search for city "Austin" in my dropdown list which could potentially give me a primary key value of 45. The picture for that primary key is not displayed until I click search for another city in the dropdown list and the page posts back to the server.
The value of the primary key is in lblRandomBar.text for the current bar displayed in the GVRandomBars but the picture of the bar associated with that recored does not appear in the gvPicsRandomBar until the search button is clicked and another "random" bar is displayed in the GVRandomBars. So I am looking at a picture in gvPicsRandomBar from the last bar that was brought up in GVRandomBars while another bars information is currently displayed in GVRadnomBars.
I am looking to have the same bar information and bar picture in both gridviews at the same time, and not one step behind like I have currently with the picture in gvPicsRandomBar. Any help would be greatly appreciated. Thanks.
ASP.NET HTML
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="Random Bar.aspx.vb" Inherits="RGVHappyHour.Featured_Bar" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<center><h2>Random Bar</h2></center>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
<asp:GridView ID="gvPicsRandomBar" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Number,Bar Name,Image" DataSourceID="SqlDataSourceRandomBarPics" ForeColor="#333333" GridLines="None" HorizontalAlign="Center" Width="548px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:ImageField DataImageUrlField="Image" HeaderText="Image" NullDisplayText="No Picture">
</asp:ImageField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceRandomBarPics" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringBars %>" SelectCommand="SELECT * FROM [Bars] WHERE ([Number] = #Number)">
<SelectParameters>
<asp:ControlParameter ControlID="lblRandomBar" Name="Number" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</p>
<p>
<asp:GridView ID="GVRandomBars" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceRandomBar" Width="548px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" DataKeyNames="Number" SelectedIndex="0">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Bar_Name" HeaderText="Bar Name" SortExpression="Bar_Name" />
<asp:BoundField DataField="Addresss" HeaderText="Addresss" SortExpression="Addresss" />
<asp:BoundField DataField="Phone_Number" HeaderText="Phone Number" SortExpression="Phone_Number" />
<asp:BoundField DataField="Days" HeaderText="Days" SortExpression="Days" />
<asp:BoundField DataField="Happy_Hour" HeaderText="Happy Hour" SortExpression="Happy_Hour" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle ForeColor="#333333" BackColor="#F7F6F3" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceRandomBar" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringBars %>" SelectCommand="SELECT TOP (1) [Number], [Bar Name] AS Bar_Name, Addresss, [Phone Number] AS Phone_Number, Days, [Happy Hour] AS Happy_Hour, [Image] AS Image FROM Bars WHERE (City = #City) ORDER BY NEWID()">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCity" Name="City" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<p>
<table class="style1" style="width: 100%">
<tr>
<td style="width: 220px; text-align: right;" class="style2">
<asp:Label ID="lblCity" runat="server" Text="City:" Font-Size="Large"
ForeColor="#47C2FF"></asp:Label>
</td>
<td style="width: 135px">
<asp:DropDownList ID="ddlCity" runat="server" DataSourceID="SqlDataSourceCity"
DataTextField="City" DataValueField="Number">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSourceCity" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringBars %>" SelectCommand="SELECT * FROM [City] ORDER BY [City]"></asp:SqlDataSource>
</td>
<td style="width: 220px; position: relative; text-align: left; vertical-align: middle;">
<asp:Button ID="btnCitySearch" runat="server" Text="Search" />
</td>
</tr>
<tr>
<td style="width: 220px" class="style2" draggable="true">
<asp:Label ID="lblRandomBar" runat="server"></asp:Label>
</td>
<td style="width: 135px">
</td>
<td style="width: 220px">
</td>
</tr>
</table>
</p>
</asp:Content>
Code Behind Random Bar.aspx.vb
Public Class Featured_Bar
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnCitySearch_Click(sender As Object, e As EventArgs) Handles btnCitySearch.Click
End Sub
Protected Sub GVRandomBars_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GVRandomBars.SelectedIndexChanged
End Sub
Protected Sub btnCitySearch_DataBinding(sender As Object, e As EventArgs) Handles btnCitySearch.DataBinding
lblRandomBar.Text = GVRandomBars.DataKeys(0).Value.ToString()
End Sub
End Class