refresh update panel from cascading drop down list - asp.net

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.

Related

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

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.

ASP.Net: Gridview throws error 'fired event RowUpdating which wasn't handled'

I have a Gridview on an ASP page bound to an SQL table. I've configured the Grid to allow Multiple updates by replacing the default Label Controls with TemplateFields using the approach described here:
Bulk Updates to Rows Bound to a GridView
Everything was working fine, until I made a change to bind the Gridview query programmatically on page load (With the aim of making the Gridview display different data depending on the user currently viewing the page) as described here:
Bind Gridview programmatically.
After making this change the page now throws the following error when the user makes changes and clicks the update button:
The GridView 'GridView1' fired event RowUpdating which wasn't handled.
Also when I try to do a single row update I get this error:
Exception Details: System.Web.HttpException: The GridView 'GridView1' fired event RowEditing which wasn't handled.
I have read many threads on similair problems but I can't seem to find a solution to my error. I don't know why dynamically binding the Gridview would cause an error in rowupdating. Appreciate any support to resolve this. Thanks.
Here's the Code:
Public Class Input
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
gvbind()
End If
End Sub
Public Sub gvbind()
Dim SqlDataSource1 As New SqlDataSource()
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
SqlDataSource1.SelectCommand = "SELECT [ID], [Project], [Description], [CAPEX], [Team] FROM [CAPEX]"
'Add Conditional Statements to change view for users/Teams
'SqlDataSource1.SelectCommand = "SELECT [ID], [Project], [Description], [CAPEX] FROM [CAPEX] where [Team] = 'Team1'"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End Sub
Private tableCopied As Boolean = False
Private originalDataTable As System.Data.DataTable
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 Up_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Up.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)
Next
' Rebind the Grid to repopulate the original values table.
tableCopied = False
GridView1.DataBind()
End Sub
Protected Function IsRowModified(ByVal r As GridViewRow) As Boolean
Dim currentID As Integer
Dim currentProject As String
Dim currentDescription As String
Dim currentCAPEX As String
currentID = Convert.ToInt32(GridView1.DataKeys(r.RowIndex).Value)
currentProject = CType(r.FindControl("ProjectTextBox"), TextBox).Text
currentDescription = CType(r.FindControl("DescriptionTextBox"), TextBox).Text
currentCAPEX = CType(r.FindControl("CAPEXTextBox"), TextBox).Text
Dim row As System.Data.DataRow = _
originalDataTable.Select(String.Format("ID = {0}", currentID))(0)
If Not currentProject.Equals(row("Project").ToString()) Then Return True
If Not currentDescription.Equals(row("Description").ToString()) Then Return True
If Not currentCAPEX.Equals(row("CAPEX").ToString()) Then Return True
Return False
End Function
Here's the Markup:
<%# Page Title="Input" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Input.aspx.vb" Inherits="WebApplication5.Input" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Data Entry
</h2>
<p>
Enter Inputs Here<asp:TextBox runat="server" Text='<%# Bind ("Project") %>'
id="TextBox4"></asp:TextBox>
<asp:Table ID="Entry" runat="server">
</asp:Table>
<asp:Button ID="TestButton" runat="server" Text="Test" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" datakeynames = "ID" Width="502px">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="ID" readOnly = "true" HeaderText="ID" SortExpression="ID"/>
<asp:TemplateField HeaderText="Project" SortExpression="Project">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Project") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="ProjectTextBox" runat="server" MaxLength="30"
Text='<%# Bind("Project") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="DescriptionTextBox" runat="server" MaxLength="150"
Text='<%# Bind("Description") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CAPEX" SortExpression="CAPEX">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("CAPEX") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="CAPEXTextBox" runat="server" MaxLength="10"
Text='<%# Bind("CAPEX") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Project], [Description], [CAPEX] FROM [CAPEX]"
DeleteCommand="DELETE FROM [CAPEX] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [CAPEX] ([ID], [Project], [Description], [CAPEX], [Team]) VALUES (#ID, #Project, #Description, #CAPEX, #Team)"
UpdateCommand="UPDATE [CAPEX] SET [Project] = #Project, [Description] = #Description, [CAPEX] = #CAPEX,[Team] = #Team WHERE [ID] = #ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="ID" Type="String" />
<asp:Parameter Name="Project" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="CAPEX" Type="Decimal" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Project" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="CAPEX" Type="Decimal" />
<asp:Parameter Name="ID" Type="String" />
<asp:Parameter Name="Team" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:Button ID="Up" runat="server" Text="Up" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
<asp:Table ID="Table1" runat="server" BorderWidth="1" BorderStyle="Solid">
</asp:Table>
</p>
You make a call in Up_Click to 'GridView1.UpdateRow()'
From the MSDN Docs:
Calling this method also raises the RowUpdated and RowUpdating events.
So all you should need to do is provide empty handlers
Adding to fnostro's answer about GridView1.UpdateRow() raising RowUpdated and RowUpdating, showing the edit button like you do:
<asp:CommandField ShowEditButton="True" />
will generate a button with CommandName="Edit". Clicking this button will raise the RowEditing event, which you also need to handle in your code.
And as a side note, since your "Update" button is outside your GridView, the CommandName property won't be responsible for automatically firing a GridView event. So not only will changing the ID from "Update" to "Up" not have any affect, but changing the CommandName wouldn't have either.
I see that SqlDataSource1 definition in codebehind lacks the UpdateCommand definition.
To be honest I always used the SqlDataSource2 approach, it'd be as easy as add DataSourceID="SqlDataSource2" and the markup would be:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" DataKeyNames = "ID"
DataSourceID="SqlDataSource2" Width="502px">
That way you can forget about if the gridview has to be bound in postbacks. Unless you place the gridview inside an UpdatePanel, I'd say it has to be bound, and then the If Not IsPostBack Then is incorrectly placed.
The code <asp:TextBox runat="server" Text='<%# Bind ("Project") %>' id="TextBox4"></asp:TextBox> looks placed outside of a databound control.

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>

VB Gridview selects wrong row for editing

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

regarding an sql query error

here is my admin.aspx.vb
Imports System.Data.SqlClient
Partial Class Admin
Inherits System.Web.UI.Page
Dim conn As New SqlConnection("Data Source=CHIRAG-PC;Initial Catalog=car;Integrated Security=True")
Dim cmd As SqlCommand
Dim drd As SqlDataReader
Dim adp As SqlDataAdapter
Dim y As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim x As Integer
x = GridView1.SelectedIndex
y = GridView1.Rows(x).Cells(1).Text
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "update carHeader set cartype='" + car.Text.ToString() + "',imagefile='" + img.Text + "',capacity=" + cap.Text + "where id=" + Convert.ToDouble(y)
conn.Open()
cmd = New SqlCommand(str, conn)
cmd.ExecuteNonQuery()
conn.Close()
End Sub
End Class
and its admin.aspx
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Admin.aspx.vb" Inherits="Admin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<br />
<br />
</asp:Content>
<asp:Content ID="Content2" runat="server" contentplaceholderid="MainContent">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=CHIRAG-PC;Initial Catalog=car;Integrated Security=True"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT * FROM [carHeader] ORDER BY [id]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" Height="149px" Width="267px">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="id" HeaderText="id"
SortExpression="id" />
<asp:BoundField DataField="cartype" HeaderText="cartype"
SortExpression="cartype" />
<asp:BoundField DataField="imagefile" HeaderText="imagefile"
SortExpression="imagefile" />
<asp:BoundField DataField="capacity" HeaderText="capacity"
SortExpression="capacity" />
</Columns>
</asp:GridView>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Image file"></asp:Label>
<asp:TextBox ID="img" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="Car Type"></asp:Label>
<asp:TextBox ID="car" runat="server"></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text="capacity"></asp:Label>
<asp:TextBox ID="cap" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Save" />
</asp:Panel>
</asp:Content>
getting an error in sql query regarding its update statement
and table contents are of carHeader:
cartype varchar ,id int,imagefile varchar,capacity int
... + cap.Text + "where ...
Notice the lack of a space before where. It's probably producing a statement like:
... field = valuewhere ...
This would break the SQL.
Additionally, it's bad practice to use string concatenation in SQL statements like this, both from a security and performance point of view. You'll want to look into using parameterized queries.
Edit: Based on your comment here:
its givin me error conversion from update set cartype=....to double type is not valid
It sounds like the error is referring to this part of the query:
set cartype='" + car.Text.ToString() + "'
What type is cartype? According to the error message, it's a double. But according to your query, you're trying to set it to a string value (by wrapping it in single quotes). If it's a double then it needs to be a numeric value, not a string.

Resources