Populate gridview only on button click - asp.net

My page consists of 4 text boxes (query filters), a submit button, and a gridview. The gridview data source is configured to take text from the 4 text boxes and filter the query results. This part works great.
This issue comes about in that for the query to function, I can't have empty text boxes or the query won't function. Something must be entered, or % for wildcard.
To be friendly for my users, I tried to set a default value of % for each of the 4 control sources(text boxes) in the gridview Data source configuration. However, since the gridview automatically populates on page load, this doesn't work since all 4 controls are set to wildcard. And when you have a DB that has hundreds of thousands of rows......
TL/DR: I want my gridview to only populate on button click, and I want blank text boxes to be accepted as wildcard (%). Ive tried a couple different code snippits concerning IsPostBack, but they didn't seem to do anything. Language = VB. Any tips you good folks can provide would be greatly appreciated. asp below:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TaxRollConnectionString %>" SelectCommand="SELECT [OWNER], [ADDRESS1], [ADDRESS2], [ADDRESS3], [CITY], [STATE], [ZIP], [WELL], [YEARBEGAN], [OPERATOR], [SURVEY], [ACRES], [TYPE], [INTEREST], [VALUE], [YEAR], [COUNTY] FROM [Owner] WHERE (([OWNER] LIKE '%' + #OWNER + '%') AND ([WELL] LIKE '%' + #WELL + '%') AND ([OPERATOR] LIKE '%' + #OPERATOR + '%') AND ([COUNTY] LIKE '%' + #COUNTY + '%'))">
<SelectParameters>
<asp:ControlParameter ControlID="textOwner" Name="OWNER" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="textWell" Name="WELL" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="textOp" Name="OPERATOR" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="textCo" Name="COUNTY" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="OWNER" HeaderText="OWNER" SortExpression="OWNER" />
<asp:BoundField DataField="ADDRESS1" HeaderText="ADDRESS1" SortExpression="ADDRESS1" />
<asp:BoundField DataField="ADDRESS2" HeaderText="ADDRESS2" SortExpression="ADDRESS2" />
<asp:BoundField DataField="ADDRESS3" HeaderText="ADDRESS3" SortExpression="ADDRESS3" />
<asp:BoundField DataField="CITY" HeaderText="CITY" SortExpression="CITY" />
<asp:BoundField DataField="STATE" HeaderText="STATE" SortExpression="STATE" />
<asp:BoundField DataField="ZIP" HeaderText="ZIP" SortExpression="ZIP" />
<asp:BoundField DataField="WELL" HeaderText="WELL" SortExpression="WELL" />
<asp:BoundField DataField="YEARBEGAN" HeaderText="YEARBEGAN" SortExpression="YEARBEGAN" />
<asp:BoundField DataField="OPERATOR" HeaderText="OPERATOR" SortExpression="OPERATOR" />
<asp:BoundField DataField="SURVEY" HeaderText="SURVEY" SortExpression="SURVEY" />
<asp:BoundField DataField="ACRES" HeaderText="ACRES" SortExpression="ACRES" />
<asp:BoundField DataField="TYPE" HeaderText="TYPE" SortExpression="TYPE" />
<asp:BoundField DataField="INTEREST" HeaderText="INTEREST" SortExpression="INTEREST" />
<asp:BoundField DataField="VALUE" HeaderText="VALUE" SortExpression="VALUE" />
<asp:BoundField DataField="YEAR" HeaderText="YEAR" SortExpression="YEAR" />
<asp:BoundField DataField="COUNTY" HeaderText="COUNTY" SortExpression="COUNTY" />
</Columns>
CodeBehind:
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
textOwner.Text = ""
textWell.Text = ""
textCo.Text = ""
textOp.Text = ""
End Sub
End Class
EDIT
I managed to fix my two main issues by removing the datasourceID from the gridview, and the following executed on click:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call BindData()
End Sub
Private Sub BindData()
With GridView1
.DataSource = SqlDataSource1
.DataBind()
End With
End Sub
However, in doing so I've managed to break the table sorting capability of the gridview. I suppose I'll find a way to do the sorting client side.

Related

Lookup value of a datalist for a gridview

4h
Hello everyone.
I have been pulling my hair out on this one. I can't see what I am doing wrong. Can someone please help.
I have a datalist which I pull value from a table. Then I want to pull values for a gridview that matches the value of the datalist. Appreciate your help!!!
My Datalist:
<asp:DataList ID="ModelCodeLabel" runat="server" DataSourceID="ModelCode"
CssClass="code" Width="250px" DataKeyField="Code">
<ItemTemplate>
<asp:Label ID="CodeLabel" runat="server" Text='<%# Eval("Code") %>' />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="ModelCode" runat="server"
ConnectionString="<%$ ConnectionStrings:TechCenterConnectionString %>"
SelectCommand="SELECT DISTINCT [Code] FROM [tblSidingModels] WHERE (([Series] = #Series) AND ([Model] = #Model))">
<SelectParameters>
<asp:ControlParameter ControlID="ddSeries" Name="Series"
PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ddModel" Name="Model"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
My Gridview:
<asp:GridView ID="GV_Performance" runat="server" Width="100%"
AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" DataSourceID="ModelPerformance"
ForeColor="Black" GridLines="None">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="ReportNo" HeaderText="ReportNo"
SortExpression="ReportNo" />
</Columns>
<FooterStyle BackColor="Tan" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<SortedAscendingCellStyle BackColor="#FAFAE7" />
<SortedAscendingHeaderStyle BackColor="#DAC09E" />
<SortedDescendingCellStyle BackColor="#E1DB9C" />
<SortedDescendingHeaderStyle BackColor="#C2A47B" />
</asp:GridView>
<asp:SqlDataSource ID="ModelPerformance" runat="server"
ConnectionString="<%$ ConnectionStrings:TechCenterConnectionString %>"
SelectCommand="SELECT DISTINCT [Code], [Description], [ReportNo] FROM [tblSidingTestReport] WHERE ([Code] = #Code)">
<SelectParameters>
<asp:ControlParameter ControlID="ModelCodeLabel" Name="Code"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Ok, so the idea is you have a datalist. User selects/clicks on that given row, and then you want to display the related data from that choice into a grid view.
I don't have your data, but let's take a data list of hotels.
When user selects a hotel, then we will display people booked in that hotel into the gv.
So, in effect we want a "cascade" from the data list to the gv.
Ok, so our simple markup for the data list is this:
<div style="float: left">
<h4>Hotels</h4>
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID">
<ItemTemplate>
<div style="float: left; width: 400px">
<h4><%# Eval("HotelName") %></h4>
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
</div>
<div style="float: left; margin-top: 5%">
<asp:Button ID="cmdSee" runat="server" Text="View Bookings" CssClass="btn"
OnClick="cmdSee_Click" />
</div>
<div style="border-bottom: 2px solid black"></div>
</ItemTemplate>
</asp:DataList>
</div>
And after data list, then the grid view like this:
<div style="float: left; margin-left: 25px">
<h4>Booked in Hotel</h4>
<asp:GridView ID="GridView1" runat="server" CssClass="table table-hover"
AutoGenerateColumns="False" DataKeyNames="ID"
Width="40%">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="Firstname" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
Ok, so the next tip/concept?
While I often still use the wizards to create the datalist or gridview?
I then blow out (delete + remove the sql data source in the current markup).
The reason for "removing" the on page SQL data source is lack of "control" over what occurs.
So, when starting out, using a wizard-based data source dropped right into that page markup can be handy, but once you want to do "more fancy" or "more complex" things, then over time, you find as a developer, you take over this automated process.
So, remove the sql data sources from your page. (and from the datalist, and gridview, ALSO remove the sql data source you specified).
We will in place of above, simple write a "small" amount of code to do the same data loading, but MORE important this ALSO gives one more control over the data loading process, and hence with more control, then the solution becomes rather simple.
Ok, so our code to load up the data list can look like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
DataList1.DataSource = Myrst("SELECT * FROM tblHotelsA ORDER BY HotelName")
DataList1.DataSource = Myrst(strSQL)
DataList1.DataBind()
End Sub
So, we now see/get this:
Ok, so now all we have to do is wire up the button click code.
that code is this:
Protected Sub cmdSee_Click(sender As Object, e As EventArgs)
Dim btn As Button = sender
Dim gRow As DataListItem = btn.NamingContainer
Dim intPK As Integer = DataList1.DataKeys(gRow.ItemIndex) ' get row click PK id
Dim strSQL = "SELECT * FROM People WHERE Hotel_ID = " & intPK
GridView1.DataSource = Myrst(strSQL)
GridView1.DataBind()
End Sub
And, to save keyboards wearing out? I have this helper routine to get my data (it returns a data table).
Public Function Myrst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using mycon As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, mycon)
mycon.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
So, when I click on a button, then I see/get this:

Reading data from a grid view into text boxes vb

I'm trying to read data retrieved into a gridview out to textboxes. My idea is to hide the gridview as im using it to retrieve data from a table that i need displayed in textboxes but i don't want the gridview to be shown.
So far i have tried this code:
Protected Sub btnFindRepair_Click(sender As Object, e As EventArgs) Handles btnFindRepair.Click
Dim row1 As GridViewRow = GridView1.SelectedRow
txtFname.Text = row1.Cells(3).Text
txtLname.Text = row1.Cells(4).Text
txtContactNum.Text = row1.Cells(5).Text
txtAltContactNum.Text = row1.Cells(6).Text
txtAddress.Text = row1.Cells(7).Text
End Sub
However this gives me the following error
An exception of type 'System.NullReferenceException' occurred in App_Web_lfjfpvke.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object
I have checked all of objects and instances and can't seem to find where the null value would come from
This is my gridview code
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2" DataKeyNames="Repair_ID">
<Columns>
<asp:BoundField DataField="Repair_ID" HeaderText="Repair_ID" SortExpression="Repair_ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="Booking_Number" HeaderText="Booking_Number" SortExpression="Booking_Number" Visible="False" />
<asp:BoundField DataField="Tracking_Number" HeaderText="Tracking_Number" SortExpression="Tracking_Number" Visible="False" />
<asp:BoundField DataField="First_Name" HeaderText="First_Name" SortExpression="First_Name" />
<asp:BoundField DataField="Last_Name" HeaderText="Last_Name" SortExpression="Last_Name" />
<asp:BoundField DataField="Contact_Number" HeaderText="Contact_Number" SortExpression="Contact_Number" />
<asp:BoundField DataField="Alternative_Contact_Number" HeaderText="Alternative_Contact_Number" SortExpression="Alternative_Contact_Number" />
<asp:BoundField DataField="Customer_Address" HeaderText="Customer_Address" SortExpression="Customer_Address" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Database %>" SelectCommand="SELECT * FROM [Customer] WHERE ([Tracking_Number] = #Tracking_Number)">
<SelectParameters>
<asp:ControlParameter ControlID="txtTrackingNumber" Name="Tracking_Number" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>

Stored Procedure not working with bulk update to rows bound to gridview

I'm using a grid view to update all rows in the grid at the same time. This code is working on another page perfectly. The difference now is that I'm calling a stored procedure since I have 3 tables I need to update. I receive no errors but nothing is getting updated in the tables. I believe that the parameters are not getting passed through properly.
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="False" DataKeyNames="CUST_ORDER_ID">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="CUST_ORDER_ID" HeaderText="ORDER_ID" SortExpression="CUST_ORDER_ID">
<ItemStyle Width="50px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="NAME" HeaderText="NAME" ReadOnly="True" SortExpression="NAME">
<ItemStyle Width="400px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ORDERDATE" HeaderText="ORDER DATE" DataFormatString="{0:d}" ReadOnly="True" SortExpression="ORDERDATE">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="DESIREDSHIPDATE" HeaderText="DESIRED SHIP DATE" SortExpression="DESIREDSHIPDATE" DataFormatString="{0:d}" ReadOnly="True" ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="PROMISEDATE" HeaderText="PROMISE DATE" SortExpression="PROMISEDATE" DataFormatString="{0:d}" ReadOnly="True" ItemStyle-Width="100">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="PROMISEDELDATE" HeaderText="DELIVERY DATE" SortExpression="PROMISEDELDATE" DataFormatString="{0:d}" ReadOnly="True" ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="TRIP_ORDER" SortExpression="TRIP_ORDER" ItemStyle-Width="500">
<EditItemTemplate>
<asp:textbox ID="TextBox3" runat="server" Text='<%# Bind("TRIP_ORDER") %>'></asp:textbox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TripOrderTextBox" runat="server" Text='<%# Bind("TRIP_ORDER") %>' Width="25px"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="25px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="ORDER_LINE_SUMMARY" HeaderText="ORDER LINE SUMMARY" SortExpression="ORDER_LINE_SUMMARY">
<ItemStyle Width="50px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="JOB_DEL_NOTES" SortExpression="JOB_DEL_NOTES" ItemStyle-Width="500">
<EditItemTemplate>
<asp:textbox ID="TextBox1" runat="server" Text='<%# Bind("JOB_DEL_NOTES") %>'></asp:textbox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="JobDelNotesTextBox" runat="server" Text='<%# Bind("JOB_DEL_NOTES") %>' Rows="3" TextMode="MultiLine" Width="500px" onkeypress="return this.value.length<=79" MaxLength="80"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="500px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="ORDER_DEL_NOTES" SortExpression="ORDER_DEL_NOTES" ItemStyle-Width="500">
<EditItemTemplate>
<asp:textbox ID="TextBox2" runat="server" Text='<%# Bind("ORDER_DEL_NOTES") %>'></asp:textbox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="OrderDelNotesTextBox" runat="server" Text='<%# Bind("ORDER_DEL_NOTES") %>' Rows="3" TextMode="MultiLine" Width="500px" onkeypress="return this.value.length<=79" MaxLength="80"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="500px"></ItemStyle>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:ConnectionStringTest %>"
ProviderName="<%$ ConnectionStrings:ConnectionStringTest.ProviderName %>"
SelectCommandType="StoredProcedure" SelectCommand="CM_GET_SCHEDULED_ORDERS"
UpdateCommandType="StoredProcedure" UpdateCommand="CM_SP_UPDATE_TRIP">
<SelectParameters>
<asp:QueryStringParameter Name="DELIVERY_DATE" DbType="DateTime" Direction="Input" QueryStringField="PROMISE_DEL_DATE" DefaultValue="" />
<asp:Parameter Name="UPDATE_TRIP" DefaultValue="YES" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="CUST_ORDER_ID" DefaultValue="" Type="String" Direction="Input" />
<asp:Parameter Name="ORDER_LINE_SUMMARY" Type="String" Direction="Input" />
<asp:Parameter Name="TRIP_ORDER" DefaultValue="" Type="String" Direction="Input"/>
<asp:Parameter Name="PROMISEDELDATE" Defaultvalue="" Type="datetime" Direction="Input"/>
<asp:Parameter Name="JOB_DEL_NOTES" Type="String" Direction="Input"/>
<asp:Parameter Name="ORDER_DEL_NOTES" Type="String" Direction="Input"/>
</UpdateParameters>
</asp:SqlDataSource>
My code behind:
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Public Class UpdateTrip
Inherits System.Web.UI.Page
Private tableCopied As Boolean = False
Private originalDataTable As System.Data.DataTable
Protected Sub Page_load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
SetDateTextBox.Text = Request.QueryString("PROMISE_DEL_DATE")
End If
End Sub
Protected Sub btnRedirect_Click(sender As Object, e As EventArgs)
Response.Redirect("~/UpdateTrip.aspx?PROMISE_DEL_DATE=" + SetDateTextBox.Text)
End Sub
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If Not tableCopied Then
originalDataTable = CType(e.Row.DataItem, System.Data.DataRowView).Row.Table.Copy()
ViewState("originalValuesDataTable") = originalDataTable
tableCopied = True
End If
End If
End Sub
Protected Sub UpdateButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles UpdateTrip.Click
originalDataTable = CType(ViewState("originalValuesDataTable"), System.Data.DataTable)
For Each r As GridViewRow In GridView1.Rows
'If IsRowModified(r) Then GridView1.UpdateRow(r.RowIndex, False)
GridView1.UpdateRow(r.RowIndex, False)
Next
' Rebind the Grid to repopulate the original values table.
'tableCopied = False
'GridView1.DataBind()
Response.Redirect("~/UpdateTrip.aspx?PROMISE_DEL_DATE=" + SetDateTextBox.Text)
End Sub
'Protected Function IsRowModified(ByVal r As GridViewRow) As Boolean
' Dim currentID As String
' Dim currentTripOrder As String
' Dim currentJobDelNotes As String
' Dim currentOrderDelNotes As String
' currentID = Convert.ToInt32(GridView1.DataKeys(r.RowIndex).Value)
' currentTripOrder = CType(r.FindControl("TripOrderTextBox"), TextBox).Text
' currentJobDelNotes = CType(r.FindControl("JobDelNotesTextBox"), TextBox).Text
' currentOrderDelNotes = CType(r.FindControl("OrderDelNotesTextBox"), TextBox).Text
' Dim row As System.Data.DataRow =
' originalDataTable.Select(String.Format("cust_order_id = {0}", currentID))(0)
' If Not currentTripOrder.Equals(row("Trip_order").ToString()) Then Return True
' If Not currentJobDelNotes.Equals(row("Job_Del_Notes").ToString()) Then Return True
' If Not currentOrderDelNotes.Equals(row("Order_Del_Notes").ToString()) Then Return True
' Return False
'End Function
Protected Sub Calendar1_SelectionChanged(sender As Object, e As EventArgs) Handles Calendar1.SelectionChanged
SetDateTextBox_PopupControlExtender.Commit(Calendar1.SelectedDate)
End Sub
End Class
Stored Procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Michael Mueller>
-- Create date: <8/3/2016>
-- Description: <update multiple tables for the trip order. customer_order. cust_order_line, cust_address>
-- =============================================
ALTER PROCEDURE [dbo].[CM_SP_UPDATE_TRIP]
-- Add the parameters for the stored procedure here
#CUST_ORDER_ID varchar(15),
#ORDER_LINE_SUMMARY VARCHAR(MAX),
#TRIP_ORDER VARCHAR(3),
#PROMISE_DEL_DATE DATETIME,
#JOB_DEL_NOTES varchar(80),
#ORDER_DEL_NOTES VARCHAR(80)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- update cust_adress with job delivery notes
UPDATE CUST_ADDRESS
SET USER_4 = #JOB_DEL_NOTES
FROM dbo.CUSTOMER_ORDER INNER JOIN
dbo.CUST_ADDRESS ON dbo.CUSTOMER_ORDER.CUSTOMER_ID = dbo.CUST_ADDRESS.CUSTOMER_ID AND
dbo.CUSTOMER_ORDER.SHIPTO_ID = dbo.CUST_ADDRESS.SHIPTO_ID
WHERE (dbo.CUSTOMER_ORDER.ID = #CUST_ORDER_ID)
-- update customer_order with order delivery notes
UPDATE CUSTOMER_ORDER
SET USER_5 = #ORDER_DEL_NOTES
WHERE ID = #CUST_ORDER_ID
-- update cust_order_line with trip_order information
IF #ORDER_LINE_SUMMARY = 'ALL LINES'
BEGIN
UPDATE CUST_ORDER_LINE
SET USER_4 = #TRIP_ORDER
WHERE CUST_ORDER_ID = #CUST_ORDER_ID
END
ELSE -- ONLY SPECIFIC LINES OF ORDER GET UPDATED
BEGIN
UPDATE CUST_ORDER_LINE
SET USER_4 = #TRIP_ORDER
WHERE CUST_ORDER_ID = #CUST_ORDER_ID AND PROMISE_DEL_DATE = #PROMISE_DEL_DATE
END
I figured out the main problem. Using Sql Server Profile I could see that only the binding fields are getting passed to the stored procedure. The other values were null. I created ItemTemplates for the remaining parameters.

Must declare the scalar variable error when inserting into Gridview

My webpage consist of a GridView, which allows the user to view, edit, and insert data. The data is inserted using a DetailView-Form, which opens via a javaScript-type window. One of the columns in the GridView consist of a company_guid, which is captured via a session that is setup in a log-in page. I'm attempting to capture the user's company_guid and log it into the Grid upon inserting data. I'm able to view and edit the Gridview, but I get the following error when I try to insert: Must declare the scalar variable "#companyguid".
The following is my Hypertext - GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Part_ID" DataSourceID="SqlDataSource1"
AutoGenerateEditButton="True" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="Part_ID" HeaderText="Part_ID"
SortExpression="Part_ID" InsertVisible="False" ReadOnly="True" Visible="false" />
<asp:BoundField DataField="Company_guid" HeaderText="Company_guid"
SortExpression="Company_guid" Visible="false" />
<asp:BoundField DataField="Part_Name" HeaderText="Part_Name"
SortExpression="Part_Name" />
<asp:BoundField DataField="Part_Desc" HeaderText="Part_Desc"
SortExpression="Part_Desc" />
<asp:CheckBoxField DataField="Active" HeaderText="Active"
SortExpression="Active" />
<asp:BoundField DataField="UpdateDate" HeaderText="UpdateDate"
SortExpression="UpdateDate" />
<asp:BoundField DataField="UpdateBy" HeaderText="UpdateBy"
SortExpression="UpdateBy" />
</Columns>
</asp:GridView>
The Detail View (this is what opens via the JavaScript Window):
<asp:DetailsView
id="dtlCarrier"
DataSourceID="SqlDataSource1"
AutoGenerateInsertButton="True"
AutoGenerateRows="False"
DefaultMode="Insert"
Runat="server" DataKeyNames="Part_ID">
<Fields>
<asp:BoundField DataField="Part_Name" HeaderText="Part_Name"
SortExpression="Part_Name" />
<asp:BoundField DataField="Part_Desc" HeaderText="Part_Desc"
SortExpression="Part_Desc" />
<asp:CheckBoxField
DataField="Active"
HeaderText="Active" SortExpression="Active" />
<asp:BoundField DataField="UpdateDate" HeaderText="UpdateDate"
SortExpression="UpdateDate" />
<asp:BoundField DataField="UpdateBy" HeaderText="UpdateBy"
SortExpression="UpdateBy" />
</Fields>
</asp:DetailsView>
<!-- the sql data source -->
<asp:SqlDataSource
ID="SqlDataSource1"
ConnectionString="<%$ ConnectionStrings:ShipperNotificationConnectionString %>"
SelectCommand="SELECT * FROM [Part]"
UpdateCommand="UPDATE Part SET Part_Name=#Part_Name,
Part_Desc=#Part_Desc, Active=#Active, UpdateDate=#UpdateDate, UpdateBy=#UpdateBy
WHERE Part_ID=#Part_ID"
InsertCommand="INSERT Part (company_guid,Part_Name,Part_Desc,Active,UpdateDate,UpdateBy)
VALUES (#companyguid,#Part_Name,#Part_Desc,#Active,#UpdateDate,#UpdateBy)"
runat="server"
/>
The code behind:
Public Class SupplierPartsMgmt
Inherits System.Web.UI.Page
'Globally declare my variable to hold the company_guid
Dim companyGuid As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'initialized companyGuid to the session varible, which is capured/stored via the log-in pg
If Not Page.IsPostBack Then
companyGuid = Session("numrecord").ToString
Else
companyGuid = Session("numrecord").ToString
End If
End Sub
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
'Dim companyGuid As String = ""
If Not String.IsNullOrEmpty(companyGuid) Then
SqlDataSource1.InsertParameters.Add("companyguid", companyGuid)
SqlDataSource1.Insert()
End If
End Sub
End Class
Could I please get some help as to what I'm doing wrong?
Drop the # in this line:
SqlDataSource1.InsertParameters.Add("companyguid", companyGuid)
# is only needed while writing the query to indicate query parameters.
And if you still need the #, i think you need to declare the <InsertParameters> elements under your asp:SqlDataSource element.
Option #1
You could declare a session based insert parameter directly as follows:
<InsertParameters>
<asp:SessionParameter Name="companyguid" SessionField="companyguid" Type="String" />
</InsertParameters>
Option #2
You can also set the company guid parameter value in the oninserting command as follows:
<InsertParameters>
<asp:Parameter Name="companyguid" Type="String" />
</InsertParameters>
OnInserting="On_Inserting" - add this attribute to your SQL Data Source
protected void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["#companyguid"].Value = valueFromSession;
}

Getting SQLDataSource Update Parameter from Gridview

I am trying to get a parameter for my update from the gridview but it is an ID column that I do not want displayed. If I display the data in a boundfield it works fine but if I set the visibility to false the parameter is no longer sent to the update stored procedure. There does not appear to be a hiddenfield column that I can put into the gridview.
I have tried to set the parameters through the code behind but I am not certain on how to access the data I want the following code does not work (It sets the parameter to nothing
Protected Sub grvFacilityDisciplineBillingRate_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles grvFacilityDisciplineBillingRate.RowUpdating
Dim row As GridViewRow = grvFacilityDisciplineBillingRate.Rows(e.RowIndex)
sqlDisciplineBillingRate.UpdateParameters("Facility_ID").DefaultValue = CInt(row.DataItem("Facility_ID"))
sqlDisciplineBillingRate.UpdateParameters("Discipline_ID").DefaultValue = CInt(row.DataItem("Discipline_ID"))
End Sub
And this is the front end with the two ID columns displayed, which is not what I want
<asp:SqlDataSource ID="sqlDisciplineBillingRate" runat="server" DataSourceMode="DataSet" SelectCommandType="StoredProcedure" SelectCommand="SP_Facility_DisciplineBillingRates" UpdateCommandType="StoredProcedure" UpdateCommand="SP_DiscplineBillingRate_Update" ConnectionString="<%$ ConnectionStrings:Trustaff_ESig2 %>">
<SelectParameters>
<asp:Parameter Name="Facility_ID" DbType="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Facility_ID" DbType="Int32" />
<asp:Parameter Name="Discipline_ID" DbType="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView ID="grvFacilityDisciplineBillingRate" runat="server" DataSourceID="sqlDisciplineBillingRate" DataKeyNames="DisciplineBillingRate_ID" AutoGenerateColumns="false" AllowSorting="true" AllowPaging="false" AutoGenerateEditButton="true" CssClass="gridview">
<EmptyDataTemplate>
There were no discipline billing rates for this facility.
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="Name" HeaderText="Discipline" SortExpression="Name" ReadOnly="true" />
<asp:BoundField DataField="BillingRate" HeaderText="Billing Rate" SortExpression="BillingRate" />
<asp:BoundField DataField="Facility_ID" HeaderText="Facility_ID" SortExpression="Facility_ID" InsertVisible="false" />
<asp:BoundField DataField="Discipline_ID" HeaderText="Discipline_ID" SortExpression="Discipline_ID" />
</Columns>
</asp:GridView>
You simply have to set the DataKeyNames e.g. DataKeyNames="Facility_ID,Discipline_ID" and the SqlDataSource will figure it out for you when using GV's Update and Delete feature.
Try using Template fields and use a label control and hide them by setting visible="false".
<asp:TemplateField HeaderText="College">
<ItemTemplate>
<asp:Label ID="lbl_Title" runat="server" text='<%# Bind("Title") %>' visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And use below code to access values from codebehind.
If gvrow.RowType = DataControlRowType.DataRow Then
Dim label1 As Label = DirectCast(gvrow.FindControl("lbl_Title"), Label)
'Access text of label using label1.text and cast to int or string
End If
You can eliminate using templated fields if you don't wish for ID columns. And still access it using datakeynames property

Resources