Stored procedure's parameter was not supplied in aspx.vb - asp.net

I want to display data in a gridview using a SQL Server stored procedure. The interface should include two textboxes for two parameters, one button, and a gridview. The data will display after all parameters are filled out and the button is clicked. But I got an error saying
'Procedure or function 'uspGetBillOfMaterials' expects parameter '#StartProductID', which was not supplied.'
Edit 1: I found out that I called parameter StartProducID instead of StartProductID. Thank you guys for helping me with this. I fixed the problem.
Now I get a new error:
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Hope you can help me figure out where is my problem and the way to fix it.
Thanks.
Edit 2: I figured out my problems and posted the answer below. Basically, I just deleted the last two rows in my code-behind and it worked.
Here is my code in ASP.NET:
Please enter StartedProduct <asp:TextBox ID="StartProductID" runat="server"></asp:TextBox>
<br />
Please enter Date <asp:TextBox ID="CheckDate" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Search BOM" />
<br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="TestProc" AutoGenerateColumns="True">
<Columns>
<asp:BoundField DataField="ProductAssemblyID" HeaderText="ProductAssemblyID" ReadOnly="True" SortExpression="ProductAssemblyID" />
<asp:BoundField DataField="ComponentID" HeaderText="ComponentID" ReadOnly="True" SortExpression="ComponentID" />
<asp:BoundField DataField="ComponentDesc" HeaderText="ComponentDesc" ReadOnly="True" SortExpression="ComponentDesc" />
<asp:BoundField DataField="TotalQuantity" HeaderText="TotalQuantity" ReadOnly="True" SortExpression="TotalQuantity" />
<asp:BoundField DataField="StandardCost" HeaderText="StandardCost" ReadOnly="True" SortExpression="StandardCost" />
<asp:BoundField DataField="ListPrice" HeaderText="ListPrice" ReadOnly="True" SortExpression="ListPrice" />
<asp:BoundField DataField="BOMLevel" HeaderText="BOMLevel" ReadOnly="True" SortExpression="BOMLevel" />
<asp:BoundField DataField="RecursionLevel" HeaderText="RecursionLevel" ReadOnly="True" SortExpression="RecursionLevel" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="TestProc" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks2014ConnectionString %>"
SelectCommand="uspGetBillOfMaterials"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="StartProductID" Name="StartProductID" PropertyName="Text" Type="Int32" />
<asp:ControlParameter ControlID="CheckDate" Name="CheckDate" PropertyName="Text" Type="DateTime" />
</SelectParameters>
</asp:SqlDataSource>
Here is my code-behind:
Public Class TestStoredProcedure
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 Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim command As New SqlCommand()
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
Dim connetionString As String = "Data Source=(local);Initial Catalog=AdventureWorks2014;Integrated Security=True"
Dim connection As New SqlConnection(connetionString)
connection.Open()
command.Connection = connection
command.CommandType = CommandType.StoredProcedure
command.CommandText = "uspGetBillOfMaterials"
command.Parameters.AddWithValue("StartProductID", StartProductID.Text)
command.Parameters.AddWithValue("#CheckDate", CheckDate.Text)
adapter = New SqlDataAdapter(command)
adapter.Fill(ds)
connection.Close()
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
End Sub
End Class

I figured out my problems:
The first error was because of a wrong parameter's name. It should be "StartProductID" instead of "StartProducID".
The second error was because I defined the gridview in both C# code and Vb code. I deleted the last two rows in my code-behind and it worked. Here is the link that helped me solve my issue.
Thank you all.

Related

Conditional render on a gridview

I have this GridView:
<asp:GridView CssClass="table table-hover mt-5" ID="OrderTable" runat="server" AutoGenerateColumns="False" DataKeyNames="Identificativo" DataSourceID="DBGestioneOrdini" OnPreRender="GridView_PreRender">
<Columns>
<asp:BoundField DataField="Identificativo" HeaderText="Identificativo" InsertVisible="False" ReadOnly="True" SortExpression="Identificativo" />
<asp:TemplateField HeaderText="Genera Fattura" HeaderStyle-CssClass="text-center" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton type="button" ID="generateInvoiace" runat="server" OnClick="generateInvoiace_Click" ForeColor="Black" CommandName="SelectRow" CommandArgument='<%# Eval("Identificativo") %>'>
<i class="fa-solid fa-file-invoice-dollar fa-lg>
</i>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
It takes the data from an Order Table. The problem here is that I need to disable the clickable icon for every record which have a specific value on a field of the db ... I can't actually realize how can i modify only certain icons since the table is rendered by asp.net and not manually
Ok, so say we have this grid view:
<asp:GridView ID="GHotels" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("Active") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hotel Information" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="Info" CssClass="btn"
OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And our code to load the grid view could be this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid
End If
End Sub
Sub LoadGrid()
Dim rstData As DataTable
rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName")
GHotels.DataSource = rstData
GHotels.DataBind()
End Sub
Public Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
rstData.TableName = strSQL
End Using
End Using
Return rstData
End Function
So no loops, just send a data table to the grid, and we now have this:
However, lets say we ONLY want the info button to show for when the hotel is active.
so, for things like totals, time formatting, color formatting, or whatever?
You use the row data bound event.
So, we can add to above this event that will "hide" the info button for any row in which the hotel is not active.
So, this code:
Protected Sub GHotels_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GHotels.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim chkActive As CheckBox = e.Row.FindControl("chkActive")
Dim cmdView As Button = e.Row.FindControl("cmdView")
If chkActive.Checked = False Then
' hide the info button
cmdView.Style.Add("display", "none")
End If
End If
End Sub
So, as noted, for running totals, highlght a row, color a row - or in this simple case hide/show the info button based on active column?
(and note you are NOT limited to just the controls on that row - you have full use of the whole database row if you wish durng the binding).
And we now see/get this:
And note once again, no looping or for next code.

Show/hide column in gridview based on Role

I have a GridView I populate, and want to show/hide the edit link based on whether the person logged in is either an Admin or User. I am not receiving any errors but cannot figure out why its not working.
aspx
<asp:GridView ID="RepView" runat="server" HeaderStyle-BackColor="#bfbfbf" HeaderStyle-ForeColor="White" HeaderStyle-Font-Underline="true" CellPadding="2" GridLines="None" AutoGenerateColumns="false" Width="990px">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="EmployeeId" HeaderText="Employee Id" />
<asp:BoundField DataField="Shift" HeaderText="Shift" />
<asp:BoundField DataField="Supervisor" HeaderText="Supervisor" />
<asp:BoundField DataField="Center" HeaderText="Center" />
<asp:BoundField DataField="DateSubmitted" HeaderText="Date Entered" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Details">
<ItemTemplate>
Edit
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind
Private Sub BindGrid()
Dim DefaultConnection As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Using con As New SqlConnection(DefaultConnection)
'This is not working...
If My.User.IsInRole("User") Then
RepView.Columns(9).Visible = False
ElseIf My.User.IsInRole("Admin") Then
RepView.Columns(9).Visible = True
End If
' End of questionable part....
Using cmd As New SqlCommand()
cmd.CommandText = ("SELECT * from Reps")
cmd.Connection = con
con.Open()
RepView.DataSource = cmd.ExecuteReader()
RepView.DataBind()
con.Close()
End Using
End Using
End Sub
Try moving your code behind "Questionable Part" from the Private Sub BindGrid() to The gridview_Load event. My guess is that what's happening is that the gridview is loading, then it gets to your code Private sub BindGrid() to show/hide columns but the columns are already loaded, therefor it can not hide them. It will continue to show the columns even after running through this code unless you run the check and show/hide the columns in the load event.
One other possible solution is that it looks like in the Private Sub BindGrid() you are trying to hide the columns before the query which means the columns will not have been created yet so you have to create the columns first before you can hide and of them. Move the questionable part down below your sql command.
Try something like this...
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim x As Integer = 0
If x = 0 Then
GridView1.Columns(0).Visible = False
Else
GridView1.Columns(0).Visible = True
End If
End Sub
I have tested this and using x = 0 will hide the first column using x = 1 will show the first column.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Sprayer_Parts_CatalogConnectionString %>"
SelectCommand="SELECT [ID], [Order#] AS column1, [Gallon], [Price] FROM [Tanks]">
</asp:SqlDataSource>

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;
}

refresh update panel from cascading drop down list

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.

Convertemptystringtonull not working in gridview

I'm trying to convert an empty string to null when editing a table in my gridview. I've tried several iterations and methods with no success. I'm suspecting that the issues is in my ObjectDataSource but don't know the correct syntax I need.
<asp:GridView
ID="grdMyDistributors"
DataSourceID = "srcGetMyDistributors"
CssClass="GridViewStyle"
DataKeyNames = "ID_Distributor"
AutoGenerateColumns = "false" AutoGenerateEditButton = "true"
GridLines="None"
runat="server" >
<Columns>
<asp:BoundField
DataField="DistributorName"
HeaderText="Distributor"
convertemptystringtonull="true"
ReadOnly = "True" />
<asp:BoundField
DataField="Distributor_Email_1"
HeaderText="Distributor Email 1"
convertemptystringtonull="true" >
<ItemStyle BackColor="#f6f17c"/>
</asp:BoundField>
<asp:BoundField
DataField="Distributor_Email_2"
HeaderText="Distributor Email 2"
convertemptystringtonull="true" >
<ItemStyle BackColor="#f6f17c"/>
</asp:BoundField>
<asp:BoundField
DataField="Minimum_Purchase_Amount"
HeaderText="Minimum Purchase Amount"
dataformatstring="{0:c}"
convertemptystringtonull="true" >
<ItemStyle BackColor="#f6f17c" />
</asp:BoundField>
</Columns>
</asp:GridView>
Here is my ObjectDataSource:
<asp:ObjectDataSource
ID="srcGetMyDistributors"
TypeName = "AAA.Distributors"
SelectMethod = "GetDistributorsPagingFiltered"
UpdateMethod = "UpdateDistributors"
EnableCaching="false"
ConvertNulltoDBNull = "true"
runat="server" >
<SelectParameters>
<asp:ProfileParameter Name="ID_Account" PropertyName="ID_Account" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter ControlID="grdMyDistributors" Name="ID_Distributor" PropertyName="SelectedValue" Type="Int32" />
</UpdateParameters>
</asp:ObjectDataSource>
Here is my update method
Public Shared Sub UpdateDistributors(ByVal ID_Distributor As Integer, ByVal Distributor_Email_1 As String, ByVal Distributor_Email_2 As String, ByVal Minimum_Purchase_Amount As Decimal)
' Initialize command
Dim con As New SqlConnection(_connectionString)
Dim cmd As New SqlCommand("UpdateDistributors", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con
' Initialize parameters
cmd.Parameters.AddWithValue("#ID_Distributor", A2AID_Restaurant_To_Distributor)
cmd.Parameters.AddWithValue("#Distributor_Email_1", Distributor_Email_1)
cmd.Parameters.AddWithValue("#Distributor_Email_2", Distributor_Email_2)
cmd.Parameters.AddWithValue("#Minimum_Purchase_Amount", Minimum_Purchase_Amount)
' Execute command
Using (con)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
When I run the code as is, I get an error saying "Object of type 'System.DBNull' cannot be converted to type 'System.String'." It's most likely erroring when it's trying to send to the Update method and expecting a string. If I take out "ConvertNulltoDBNull = "true" from the ObjectDataSource it complains that the SQL statement is expecting a value (meaning it's not sending the Null). I've tried so many variations of this and can't find any info in the class library. Any help would be greatly appreciated!
Thanks in advance!
use eval() for your gridview Columns
<%# Eval("DistributorName") == DBNull.Value ? "" : value.ToString()%>
(its in C#)
<asp:GridView
ID="grdMyDistributors"
DataSourceID = "srcGetMyDistributors"
CssClass="GridViewStyle"
DataKeyNames = "ID_Distributor"
AutoGenerateColumns = "false"
AutoGenerateEditButton = "true"
GridLines="None"
runat="server" >
<Columns>
<asp:TemplateField HeaderText="Seniority">
<ItemTemplate>
<%# Eval("DistributorName") == DBNull.Value ? "" :Eval("DistributorName").ToString()%>
</ItemTemplate>
</asp:TemplateField>
</Columns>

Resources