I have been trying to pass selected data from two dropdownlist (page1.aspx) to (page2.aspx) I am not having any luck as it seems the data is not being passed when selected. Please help, this doesn't seem that difficult, but I can not get it work. On (page2.aspx) the data from the dropdownlists will be passed to a stored procedure and all results will be in a gridview.
Here is my code:
Page1.aspx
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="ST_Code" DataValueField="ST_Code" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbConnection %>"SelectCommand="SELECT [ST_Code] FROM [State]">
</asp:SqlDataSource> City: <asp:DropDownList ID="ddlCity" runat="server" DataSourceID="SqlDataSource2" DataTextField="RS_City" DataValueField="RS_City" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:dbConnection %>"SelectCommand="ListbyStateSPROC"SelectCommandType="StoredProcedure">`
<SelectParameters>
<asp:ControlParameter ControlID="ddlState" Name="State" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</asp:Content>
Page1.aspx.vb
Imports System.Data
Imports System.Data.Common
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls.DataGrid
Imports System.Web.UI.WebControls.DropDownList
Partial Public Class LiveEventSearch
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Sub ddlState_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
SqlDataSource2.SelectParameters.Clear()
SqlDataSource2.SelectParameters.Add(New Parameter("#State", DbType.String, ddlState.SelectedValue))
ddlCity.DataBind()
End Sub
Protected Sub ddlCity_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCity.SelectedIndexChanged
End Sub
Protected Sub Submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit.Click
End Sub
End Class
Page2.aspx
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" Style="z-index: 100; left: 324px; position: absolute;
top: 226px">
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" ReadOnly="True" SortExpression="R_Code" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="R_Name" />
<asp:BoundField DataField="Number" HeaderText="Number" ReadOnly="True" SortExpression="RS_Number" />
<asp:BoundField DataField="Addr_1" HeaderText="Addr_1" ReadOnly="True" SortExpression="RS_Addr_1" />
<asp:BoundField DataField="City" HeaderText="City" ReadOnly="True" SortExpression="RS_City" />
<asp:BoundField DataField="State" HeaderText="State" ReadOnly="True" SortExpression="RS_State" />
<asp:BoundField DataField="RS_Zip" HeaderText="RS_Zip" ReadOnly="True" SortExpression="RS_Zip" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbConnection %>"
SelectCommand="ListbyCityStSPROC" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:QueryStringParameter Name="City" QueryStringField="RS_City" Type="String" />
<asp:QueryStringParameter Name="State" QueryStringField="ST_Code" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
Effectively each page in an ASP.NET application is like a single app in itself, things don't last across pages, so you either need to implement a class that keeps hold of your SQLDataSource so can call it across pages or you need to implement some way to copy the data across the pages.
You could also use the FindControl function to find the SQLDataSource across pages:
SqlDataSource sql = (SqlDataSource)Page.Master.Findcontrol("SqlDataSource1");
Related
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:
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.
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;
}
I am developing a webpage that will utilize two cascading drop down lists and an update panel that contains a nested gridview.
I have managed to get the cascading drop down lists to work correctly, and I have also managed to get my nested gridview working.
The next step is to populate the gridview based on the selection of the second cascading drop down list, which is where the update panel comes into play. I figured that once a selection has been made to the second drop down list, I could then refresh the update panel and load my nested gridviews. Looking through the documentation, I realized that I needed a trigger of some sort to force the update panel to reload, but I must not be doing something correctly...
Within my update panel, I use the trigger parameter, where cddMachine is the name of the second drop down list.
<Triggers>
<asp:AsyncPortBackTrigger ControlID="cddMachine" EventName="SelectedIndexChanged" />
</Triggers>
Upon running my code, the following error is thrown:
Control with ID 'cddMachine' being registered through
RegisterAsyncPostBackControl or RegisterPostBackControl must implement either
INamingContainer, IPostBackDataHandler, or IPostBackEventHandler
After searching for a while, I have been unable to find any clear information as to how one would go about refreshing an update panel by means of a cascading drop down list. I'm sure I'm overlooking something simple, but I am not sure what it is that I need to look for.
EDIT - Included code
lockout.aspx
<%# Page Title="" Language="vb" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="Lockout.aspx.vb" Inherits="LockoutTagout.Lockout" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="asm" runat="server" />
<div>
Complex:
<asp:DropDownList ID="ComplexList" runat="server" />
Machine:
<asp:DropDownList ID="MachineList" runat="server" AutoPostBack="true" />
<asp:CascadingDropDown ID="cddComplex" runat="server"
ServicePath="~/lockoutService.asmx" ServiceMethod="GetComplex"
TargetControlID="ComplexList" Category="Complex"
PromptText="Select Complex" />
<asp:CascadingDropDown ID="cddMachine" runat="server"
ServicePath="~/lockoutService.asmx" ServiceMethod="GetMachine"
TargetControlID="MachineList" ParentControlID="ComplexList"
Category="Machine" PromptText="Select Machine" />
</div>
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LOTOConnectionString %>"
SelectCommand="SELECT * FROM [DEVICES] WHERE machine_id = #machine_id">
<SelectParameters>
<asp:ControlParameter Name="machine_id" ControlID="cddMachine" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" GridLines="None" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="devices_id" DataSourceID="SqlDataSource1" AlternatingRowStyle-BackColor="White">
<Columns>
<asp:BoundField DataField="devices_id" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="devices_id" />
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="description" HeaderText="Description" SortExpression="description" />
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="location" HeaderText="Location" SortExpression="location" />
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="verification" HeaderText="Verification" SortExpression="verification" />
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="rack_num" HeaderText="Rack_#" SortExpression="rack_num" />
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="section_num" HeaderText="Section_#" SortExpression="section_num" />
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="color_or_number" HeaderText="Key_Identifier" SortExpression="color_or_number" />
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="normal_position" HeaderText="Normal_Position" SortExpression="normal_position" />
<asp:TemplateField HeaderText="P&P Numbers" ControlStyle-Width="100px">
<ItemTemplate>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:LOTOConnectionString %>" SelectCommand="SELECT * FROM [PNP] WHERE ([devices_id] = #devices_id)">
<SelectParameters>
<asp:Parameter Name="devices_id" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView2" ShowHeader="false" GridLines="None" runat="server" AutoGenerateColumns="False" DataKeyNames="pnp_id" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="pnp_num" HeaderText="pnp_num" SortExpression="pnp_num" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#a52138" ForeColor="White" Font-Size="Medium" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
lockout.aspx.vb
Public Class Lockout
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load, MachineList.SelectedIndexChanged
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
Dim s As SqlDataSource = CType(e.Row.FindControl("SqlDataSource2"), SqlDataSource)
s.SelectParameters(0).DefaultValue = e.Row.Cells(0).Text
End If
End Sub
End Class
lockoutService.asmx.vb
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports AjaxControlToolkit
Imports System.Data.SqlClient
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class lockoutService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetComplex(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim conn As New SqlConnection("Data Source=WIWRMS-SQLD2\SQLD2;Initial Catalog=LOTO;Persist Security Info=True;User ID=LOTO_ADMIN;Password=lotoadmin")
conn.Open()
Dim comm As New SqlCommand( _
"SELECT * FROM complex", conn)
Dim dr As SqlDataReader = comm.ExecuteReader()
Dim l As New List(Of CascadingDropDownNameValue)
While (dr.Read())
l.Add(New CascadingDropDownNameValue(dr("complex_name").ToString(), dr("complex_id").ToString()))
End While
conn.Close()
Return l.ToArray()
End Function
<WebMethod()> _
Public Function GetMachine(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim complex_id As Integer
Dim kv As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
If Not kv.ContainsKey("complex") Or Not Int32.TryParse(kv("complex"), complex_id) Then
Throw New ArgumentException("Couldn't find complex.")
End If
Dim conn As New SqlConnection("Data Source=WIWRMS-SQLD2\SQLD2;Initial Catalog=LOTO;Persist Security Info=True;User ID=LOTO_ADMIN;Password=lotoadmin")
conn.Open()
Dim comm As New SqlCommand( _
"SELECT * FROM machine WHERE complex_id = #complex_id", conn)
comm.Parameters.AddWithValue("#complex_id", complex_id)
Dim dr As SqlDataReader = comm.ExecuteReader()
Dim l As New List(Of CascadingDropDownNameValue)
While (dr.Read())
l.Add(New CascadingDropDownNameValue(dr("machine_name").ToString(), dr("machine_id").ToString()))
End While
conn.Close()
Return l.ToArray()
End Function
End Class
A CascadingDropDown is really just an extender on a DropDownList, so you should be able to remove the trigger, set your final DropDownList's AutoPostBack property to true, then handle its SelectedIndexChanged event. That should automatically trigger the PartialPostBack so that you can update your GridView accordingly.
Additional details for fix:
I'm thinking you may want to change the following in your DataSource markup: <asp:ControlParameter Name="machine_id" ControlID="cddMachine" PropertyName="SelectedValue" /> change ControlID to MachineList.
Hello I have a searchbox and when I search for a record it is fine the records shows up however once I click edit on the gridview the page does a postback and all the records show back up with the first record selected for editing. How can I disable this post back or make it when I click edit all the records do not display again?
VB.CodeBehind
Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
txtSearch.text = ""
sourcegridview.DataBind()
End Sub
Protected Sub btnSearch_Click(sender As Object, e As System.EventArgs) Handles btnSearch.Click
SqlDataSource1.SelectCommand = "select * from Stg_Employee_All_Info where Name like '%" & txtSearch.Text & "%'"
SqlDataSource1.DataBind()
End Sub
Gridview Code
<asp:GridView ID="sourcegridview" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="SqlDataSource1" Width="422px" AllowSorting="True"
DataKeyNames="Row">
<Columns>
<asp:BoundField DataField="Row" HeaderText="Row"
SortExpression="Row" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True"
SortExpression="Name" />
<asp:BoundField DataField="Dept" HeaderText="Dept" ReadOnly="True"
SortExpression="Dept" />
<asp:TemplateField HeaderText="Hide_Bday">
<EditItemTemplate>
<asp:CheckBox ID="chkBday" runat="server" Checked='<%# Bind("Hide_Bday") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHideBday" runat="server" Text='<%# Eval("Hide_Bday") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hide_Anniv">
<EditItemTemplate>
<asp:CheckBox ID="chkAnniv" runat="server"
Checked='<%# Bind("Hide_Anniv") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHideAnniv" runat="server" Text='<%# Eval("Hide_Anniv") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<EmptyDataTemplate>
<asp:CheckBox ID="chkboxHideBday" runat="server"
Checked='<%# Eval("Hide_Bday") %>' Visible='<%# Eval("Hide_Bday") %>' />
</EmptyDataTemplate>
I populate and update the gridview with a sqldatasource which references a stored procedure
Gridview populate code
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:a_Kronos %>"
SelectCommand="SELECT [Row], [Name], [Dept], [Hide_Bday], [Hide_Anniv] FROM [Stg_Employee_All_Info]"
UpdateCommand="usp_insertoptout" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="Hide_Bday" Type="Int32" />
<asp:Parameter Name="Hide_Anniv" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
The problem is when you click on search it sets the SelectCommand, but only for that single round-trip to the server. The SelectCommand is not persisted anywhere so when you are clicking "Edit", the grid goes right back to using SqlDataSource1's initial command.
Early versions of the ASP.NET GridView stored the SelectCommand text in ViewState, but that was removed for security reasons. As they put it:
For security purposes, the SqlDataSource control no longer stores commands in ViewState by default. Since it is technically possible to decode the contents of ViewState on the client, storing sensitive information about the database backend in this field could expose you to an information disclosure threat.
So instead, you will need to bind the Grid manually and find your way of persisting the SelectCommand across multiple post-backs. Here is an example using Session:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
SqlDataSource1.SelectCommand = If(Session("SearchSelectCommand"), "SELECT [Row], [Name], [Dept], [Hide_Bday] ...")
SqlDataSource1.DataBind()
End Sub
Protected Sub btnSearch_Click(sender As Object, e As System.EventArgs) Handles btnSearch.Click
Dim searchQuery As String = "select * from Stg_Employee_All_Info where ..."
Session("SearchSelectCommand") = searchQuery
SqlDataSource1.SelectCommand = searchQuery
SqlDataSource1.DataBind()
End Sub