How to Change SQLDatasource Parameter on button press - asp.net

I have a Gridview which is populating with entries fine.
What i need to do is enable it, so that when a string is entered within the textbox, it changes the SQLDatasource parameter to search for entries that match.
So this is the ASPx file that is being used.
<%# Page Language="vb" AutoEventWireup="True" CodeBehind="test.aspx.vb" MasterPageFile="~/Site1.Master"%>
<asp:Content ID="content" runat="server" ContentPlaceHolderID="Content">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<span class="country"></span>
<div align="right">
<asp:TextBox runat="server" ID="textbox1"></asp:TextBox>
<asp:Button runat="server" Text="Search" ID="Button1" OnClientClick="Button1_click" PostBackUrl="~/test.aspx" />
</div>
<br />
<br />
<div align="center">
<asp:UpdatePanel runat="server" ID="updatepanel">
<ContentTemplate>
<asp:SqlDataSource runat="server" ID="datab" SelectCommand="SELECT * FROM [TEST] where [unit]=#unit" ConnectionString="<%$ ConnectionStrings:Con %>" ProviderName="<%$ ConnectionStrings:Con.ProviderName %>">
<SelectParameters>
<asp:Parameter DefaultValue="UK" Name="unit" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="View" DataSourceID="datab" runat="server" CssClass="table" AllowSorting="True" AutoGenerateColumns="True" DataKeyNames="Id">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
The above works absolutley fine, I can change the parameter manually, and it will work. However i cannot get it to update from user submission.
Backfile:
Public Class test
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim unit As String = textbox1.Text
datab.UpdateParameters("Unit").DefaultValue = unit
updatepanel.Update()
End Sub
End Class
I'm guessing that i am doing something wrong when referrencing the code behind page, as the page seems to refresh when i press the button.
Any help is appreciated.
******Edit********
I have tried to use the following code in the behind file, however it does not display anything on the actual page now.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim DS As SqlDataSource = New SqlDataSource
Dim con As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\local\test.accdb"
Dim sc As String = "SELECT * FROM [TEST] where [unit]=#unit"
DS.ID = "datab"
DS.ConnectionString = con
DS.SelectCommand = sc
DS.SelectParameters("Unit").DefaultValue = "UK"
View.DataSource = datab
View.DataBind()
End Sub

Related

Fill GridView based on DropDownList.SelectedValue and Button Click

struggling since morning. the scenario is as follow:
I have a ASP.NET web page having
two dropdownlist
two buttons
One GridView
Wants to fill gridview based on dropdownlist selected value
here is the .aspx code
<%# Page Title="" Language="VB" MasterPageFile="~/Admin/ADMIN.master" AutoEventWireup="false" CodeFile="EditSTUdetail.aspx.vb" Inherits="Admin_EditSTUdetail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<style type="text/css">
.auto-style1
{
height: 42px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div align="center">
<fieldset>
<legend style="font-size: 16px;">SEARCH / EDIT / DELETE STUDENT RECORDS
</legend>
<div style="overflow: auto">
<div>
<asp:Label ID="lblMsg" runat="server" CssClass="lblresponse" />
<table style="margin: 3px auto 1px auto; height: 72px;">
<tr>
<td style="text-align: right;" class="auto-style2">Select Session/सत्र का चयन करें :
</td>
<td class="auto-style3">
<asp:DropDownList ID="ddlSession" runat="server" AppendDataBoundItems="True" Width="236px" Height="28px">
<asp:ListItem Text="--Select Session--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="ddlSession" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td style="text-align: right;" class="auto-style1">Select Course /कक्षा का चयन करें :
</td>
<td>
<asp:DropDownList ID="ddlCourse" runat="server" AppendDataBoundItems="true" Width="236px" Height="28px">
<asp:ListItem Text="--Select Course--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="ddlCourse" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td class="auto-style1"></td>
<td class="auto-style1">
<asp:Button ID="btnSearch" runat="server" Text="SEARCH" CssClass="button" OnClick="btnSearch_Click" Height="34px" Width="77px" /></td>
<td colspan="2" class="auto-style1">
<asp:Button ID="btnRefresh" runat="server" Text="REFRESH" CssClass="button" OnClick="btnRefresh_Click" Height="34px" Width="77px" /></td>
</tr>
</table>
</div>
</div>
<asp:GridView ID="GVdata" runat="server" Width="674px" CaptionAlign="Top"
AutoGenerateColumns="False" Height="100px" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" GridLines="Vertical"
EmptyDataText="There Are No Record Found" OnRowCancelingEdit="gvManageOrders_RowCancelingEdit"
OnRowDeleting="gvManageOrders_RowDeleting" OnRowEditing="gvManageOrders_RowEditing"
OnRowUpdating="gvManageOrders_RowUpdating">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Sr. No." ItemStyle-Width="20">
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit/Remove" ShowDeleteButton="True"
ShowEditButton="True" DeleteText="Remove" />
<asp:TemplateField HeaderText="Student ID" Visible="True">
<ItemTemplate>
<asp:Label ID="studentID" runat="server" Text='<%# Bind("studentID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Sname" runat="server" Text='<%# Bind("Sname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Father's Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Fname" runat="server" Text='<%# Bind("Fname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle BackColor="#eeeeee" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px" Font-Size="Large" ForeColor="#851010"
HorizontalAlign="Center" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#851010" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#851010" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</fieldset>
</div>
</asp:Content>
and here is my vb code:
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Net.Mail
Imports System.Data
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Partial Public Class Admin_EditSTUdetail
Inherits System.Web.UI.Page
Private myds As DataSet
Protected Sub LoadSession()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("select sessionID, session from tblcategories ORDER by session DESC", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlSession.DataTextField = ds.Tables(0).Columns("session").ToString()
' text field name of table dispalyed in dropdown
ddlSession.DataValueField = ds.Tables(0).Columns("sessionID").ToString()
' to retrive specific textfield name
ddlSession.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlSession.DataBind()
ddlSession.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub LoadCourse()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("SELECT DISTINCT course AS mycolumn FROM " _
& " tblsubjects where course is not null and " _
& "not course = '' order by mycolumn", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlCourse.DataTextField = ds.Tables(0).Columns("mycolumn").ToString()
' text field name of table dispalyed in dropdown
ddlCourse.DataValueField = ds.Tables(0).Columns("mycolumn").ToString()
' to retrive specific textfield name
ddlCourse.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlCourse.DataBind()
ddlCourse.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub fillgrid()
Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
Dim cmd As New SqlCommand("SELECT StudentID,session,course,Sname,Fname FROM [tblstudetail] WHERE " _
& " [session] = '" + ddlSession.SelectedValue.ToString() + "' AND " _
& " [course] = '" + ddlCourse.SelectedValue.ToString() + "'", cn)
cn.Open()
Dim da As New SqlDataAdapter(cmd)
myds = New DataSet()
da.Fill(myds)
GVdata.DataSource = myds
GVdata.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadSession()
LoadCourse()
fillgrid()
End If
End Sub
Protected Sub gvManageOrders_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowEditing(sender As Object, e As GridViewEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If Not Page.IsPostBack Then
fillgrid()
End If
End Sub
Protected Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
GVdata.DataSource = Nothing
End Sub
End Class
But it is not returning what i request.
Kindly HELP me out this....
PLease remove these lines ,
ddlSession.SelectedIndex = -1
ddlCourse.SelectedIndex = -1
from the end of the LoadCourse and LoadSession methods. These are resetting the dropdown values and causing issue.
The flow is messed up in your code. You are calling loadsession , loadcourses and fillgrid serially from the page load method. Think about it. When the code in fillgrid executes there is no selected value in the drop downs. Obviously no data is found and so the gridview is not visible.
The better way to handle is introduce two new methods like this,
Protected Sub ddlCourses_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlSession.SelectedIndexChanged
and
Protected Sub ddlAC3_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlCourse.SelectedIndexChanged
Inside these methods send out a call to fillgrid.
Also inside the fillgrid method first validate there is some value in both the ddlCourse and ddlSession dropdowns , then send out the database command.
First of all
ddlSession.SelectedValue.ToString()
become
ddlSession.SelectedValue
Then in Protected Sub btnSearch_Click remove
If Not Page.IsPostBack Then
Then
ddlCourse.SelectedIndex = -1
become
ddlCourse.ClearSelection();
Finally, are you sure there aren't NULL value in the database?

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.

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.

whole page get refreshed on grid sorting even after using updatepanel

I have two grids on one page both are independent but when i sort one grid then page get refreshed and sorting on other grid dissapears.
I have used update panel but still it not works...
Please help me out...
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>
<table>
<tr>
<td>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="grvDemo" runat="server" AllowSorting="true" AutoGenerateColumns="true" EnableSortingAndPagingCallbacks="TRUE">
</asp:GridView>
</ContentTemplate>
<Triggers> <asp:AsyncPostBackTrigger ControlID="grvDemo" EventName="grvDemo_Sorting" /> </Triggers>
</asp:UpdatePanel>
</td>
<td>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true" AutoGenerateColumns="true" EnableSortingAndPagingCallbacks="TRUE">
</asp:GridView>
</ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger ControlID="GridView1" EventName="GridView1_Sorting" /></Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>
Code:
Partial Class Import_ETL_Popup
Inherits Syscon.Web.UI.Page.baseClass
Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
bindgrid()
End Sub
Public Function bindgrid()
Dim dt As DataTable = DBHelper.ExecuteDataset(FunctionFactory.GetConnectionString(), CommandType.Text, "select user_name,password from tbl_user_mst").Tables(0)
grvDemo.DataSource = dt
grvDemo.DataBind()
Dim dt1 As DataTable = DBHelper.ExecuteDataset(FunctionFactory.GetConnectionString(), CommandType.Text, "select password,user_name from tbl_user_mst order by user_name").Tables(0)
GridView1.DataSource = dt1
GridView1.DataBind()
End Function
Protected Sub grvDemo_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grvDemo.Sorting
Dim dt As DataTable = DBHelper.ExecuteDataset(FunctionFactory.GetConnectionString(), CommandType.Text, "select user_name,password from tbl_user_mst order by user_name desc").Tables(0)
grvDemo.DataSource = dt
grvDemo.DataBind()
End Sub
Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
Dim dt1 As DataTable = DBHelper.ExecuteDataset(FunctionFactory.GetConnectionString(), CommandType.Text, "select password,user_name from tbl_user_mst order by user_name desc").Tables(0)
GridView1.DataSource = dt1
GridView1.DataBind()
End Sub
End Class
You are providing wrong EventName in your UpdatePanel controls
For more info on this topic Go here
Actually you don't have to provide the event handler in that EventName property of your UpdatePanel controls, You just need to provide the name of the event like click is the name of an event provided by a button control.
try this
<asp:AsyncPostBackTrigger ControlID="grvDemo" EventName="OnSorting" />
and this
<asp:AsyncPostBackTrigger ControlID="GridView1" EventName="OnSorting" />

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