Lookup value of a datalist for a gridview - asp.net

4h
Hello everyone.
I have been pulling my hair out on this one. I can't see what I am doing wrong. Can someone please help.
I have a datalist which I pull value from a table. Then I want to pull values for a gridview that matches the value of the datalist. Appreciate your help!!!
My Datalist:
<asp:DataList ID="ModelCodeLabel" runat="server" DataSourceID="ModelCode"
CssClass="code" Width="250px" DataKeyField="Code">
<ItemTemplate>
<asp:Label ID="CodeLabel" runat="server" Text='<%# Eval("Code") %>' />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="ModelCode" runat="server"
ConnectionString="<%$ ConnectionStrings:TechCenterConnectionString %>"
SelectCommand="SELECT DISTINCT [Code] FROM [tblSidingModels] WHERE (([Series] = #Series) AND ([Model] = #Model))">
<SelectParameters>
<asp:ControlParameter ControlID="ddSeries" Name="Series"
PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ddModel" Name="Model"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
My Gridview:
<asp:GridView ID="GV_Performance" runat="server" Width="100%"
AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" DataSourceID="ModelPerformance"
ForeColor="Black" GridLines="None">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="ReportNo" HeaderText="ReportNo"
SortExpression="ReportNo" />
</Columns>
<FooterStyle BackColor="Tan" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<SortedAscendingCellStyle BackColor="#FAFAE7" />
<SortedAscendingHeaderStyle BackColor="#DAC09E" />
<SortedDescendingCellStyle BackColor="#E1DB9C" />
<SortedDescendingHeaderStyle BackColor="#C2A47B" />
</asp:GridView>
<asp:SqlDataSource ID="ModelPerformance" runat="server"
ConnectionString="<%$ ConnectionStrings:TechCenterConnectionString %>"
SelectCommand="SELECT DISTINCT [Code], [Description], [ReportNo] FROM [tblSidingTestReport] WHERE ([Code] = #Code)">
<SelectParameters>
<asp:ControlParameter ControlID="ModelCodeLabel" Name="Code"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

Ok, so the idea is you have a datalist. User selects/clicks on that given row, and then you want to display the related data from that choice into a grid view.
I don't have your data, but let's take a data list of hotels.
When user selects a hotel, then we will display people booked in that hotel into the gv.
So, in effect we want a "cascade" from the data list to the gv.
Ok, so our simple markup for the data list is this:
<div style="float: left">
<h4>Hotels</h4>
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID">
<ItemTemplate>
<div style="float: left; width: 400px">
<h4><%# Eval("HotelName") %></h4>
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
</div>
<div style="float: left; margin-top: 5%">
<asp:Button ID="cmdSee" runat="server" Text="View Bookings" CssClass="btn"
OnClick="cmdSee_Click" />
</div>
<div style="border-bottom: 2px solid black"></div>
</ItemTemplate>
</asp:DataList>
</div>
And after data list, then the grid view like this:
<div style="float: left; margin-left: 25px">
<h4>Booked in Hotel</h4>
<asp:GridView ID="GridView1" runat="server" CssClass="table table-hover"
AutoGenerateColumns="False" DataKeyNames="ID"
Width="40%">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="Firstname" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
Ok, so the next tip/concept?
While I often still use the wizards to create the datalist or gridview?
I then blow out (delete + remove the sql data source in the current markup).
The reason for "removing" the on page SQL data source is lack of "control" over what occurs.
So, when starting out, using a wizard-based data source dropped right into that page markup can be handy, but once you want to do "more fancy" or "more complex" things, then over time, you find as a developer, you take over this automated process.
So, remove the sql data sources from your page. (and from the datalist, and gridview, ALSO remove the sql data source you specified).
We will in place of above, simple write a "small" amount of code to do the same data loading, but MORE important this ALSO gives one more control over the data loading process, and hence with more control, then the solution becomes rather simple.
Ok, so our code to load up the data list can look like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
DataList1.DataSource = Myrst("SELECT * FROM tblHotelsA ORDER BY HotelName")
DataList1.DataSource = Myrst(strSQL)
DataList1.DataBind()
End Sub
So, we now see/get this:
Ok, so now all we have to do is wire up the button click code.
that code is this:
Protected Sub cmdSee_Click(sender As Object, e As EventArgs)
Dim btn As Button = sender
Dim gRow As DataListItem = btn.NamingContainer
Dim intPK As Integer = DataList1.DataKeys(gRow.ItemIndex) ' get row click PK id
Dim strSQL = "SELECT * FROM People WHERE Hotel_ID = " & intPK
GridView1.DataSource = Myrst(strSQL)
GridView1.DataBind()
End Sub
And, to save keyboards wearing out? I have this helper routine to get my data (it returns a data table).
Public Function Myrst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using mycon As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, mycon)
mycon.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
So, when I click on a button, then I see/get this:

Related

ASPxGridView doesnot get updated on submitting FormLayout field values through submit button

I have FormLayout element and ASPxGridView element (these are devExpress elements) on the same page as shown in Figure below:
Screenshot of my web Application
When I Enter Values for date and reading the value gets stored in database but the ASPxGridView below the form does not get update unless I re-run the project. Any help in this regard is well appreciated. Regards. My .aspx and vb codes are given below:
.aspx code
\<%# Page Title="" Language="VB" MasterPageFile="\~/Site.master" AutoEventWireup="false" CodeFile="meter_reading.aspx.vb" Inherits="Default2" %\>
\<%# Register Assembly="DevExpress.Web.Bootstrap.v22.1, Version=22.1.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web.Bootstrap" TagPrefix="dx" %\>
\<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server"\>
<div class="content-wrapper">
<dx:ASPxFormLayout ID="ASPxFormLayout1" runat="server" ClientInstanceName="ASPxFormLayout1">
<Items>
<dx:LayoutItem Caption="Date" ColSpan="1" Name="cbo_date">
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer runat="server">
<dx:ASPxDateEdit ID="date" runat="server" ClientInstanceName="date">
</dx:ASPxDateEdit>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
<dx:LayoutItem Caption="reading" ColSpan="1" Name="txt_reading" RequiredMarkDisplayMode="Required" HelpText="enter reading">
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer runat="server">
<dx:ASPxTextBox ID="txt_reading" runat="server" ClientInstanceName="txt_reading">
<ValidationSettings>
<RegularExpression ErrorText="Enter a Decimal number" ValidationExpression="\d+" />
<RequiredField IsRequired="True" ErrorText="This field is mandatory" />
</ValidationSettings>
</dx:ASPxTextBox>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
<dx:LayoutItem Caption="" ColSpan="1" Name="btn_submit">
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer runat="server">
<dx:ASPxButton ID="btn_submit" runat="server" Text="Submit" ClientInstanceName="btn_submit">
<ClientSideEvents Click="onClick"/>
<%--<ClientSideEvents Click="function(s, e) {
txt_reading.Text = "";
date.Value = "null";--%>
<%--}" />--%>
</dx:ASPxButton>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
</Items>
</dx:ASPxFormLayout>
</div>
<div class="content-wrapper">
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False" DataSourceID="Energy_ds" KeyFieldName="ID" Width="700px" ClientInstanceName="ASPxGridView1" CssClass="col-lg-1" EnablePagingCallbackAnimation="True" Caption="Data Record">
<Settings ShowFooter="True" ShowGroupFooter="VisibleIfExpanded" />
<SettingsPopup>
<EditForm Modal="True">
</EditForm>
<FilterControl AutoUpdatePosition="False"></FilterControl>
</SettingsPopup>
<SettingsSearchPanel Visible="True" />
<Columns>
<dx:GridViewCommandColumn ShowDeleteButton="True" ShowEditButton="True" ShowNewButtonInHeader="True" VisibleIndex="0">
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn FieldName="ID" ReadOnly="True" ShowInCustomizationForm="True" Visible="False" VisibleIndex="1">
<EditFormSettings Visible="False" />
</dx:GridViewDataTextColumn>
<dx:GridViewDataDateColumn FieldName="date" ShowInCustomizationForm="True" VisibleIndex="2">
</dx:GridViewDataDateColumn>
<dx:GridViewDataTextColumn FieldName="reading" ShowInCustomizationForm="True" VisibleIndex="3">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="price" ReadOnly="True" ShowInCustomizationForm="True" VisibleIndex="4">
<EditFormSettings Visible="False" />
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="difference_next_reading" ShowInCustomizationForm="True" VisibleIndex="5">
<PropertiesTextEdit DisplayFormatString="{0} km">
</PropertiesTextEdit>
<EditFormSettings Visible="False" />
</dx:GridViewDataTextColumn>
</Columns>
<TotalSummary>
<dx:ASPxSummaryItem DisplayFormat="Total Reading = {0} km" FieldName="difference_next_reading" ShowInColumn="difference_next_reading" SummaryType="Sum" ValueDisplayFormat="{0} km" />
</TotalSummary>
<Styles>
<Footer BackColor="White" Font-Bold="True">
</Footer>
</Styles>
</dx:ASPxGridView>
<asp:SqlDataSource ID="Energy_ds" runat="server" ConnectionString="<%$ ConnectionStrings:sundayConnectionString %>" DeleteCommand="DELETE FROM [meter_reading] WHERE [ID] = #ID" InsertCommand="INSERT INTO [meter_reading] ([date], [reading]) VALUES (#date, #reading)" SelectCommand="SELECT ID, date,reading, price, lead(reading) OVER (ORDER BY date ) - reading AS difference_next_reading FROM meter_reading ORDER BY date" UpdateCommand="UPDATE [meter_reading] SET [date] = #date, [reading] = #reading WHERE [ID] = #ID" ProviderName="<%$ ConnectionStrings:sundayConnectionString.ProviderName %>">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter DbType="Date" Name="date" />
<asp:Parameter Name="reading" Type="Double" />
<asp:Parameter Name="price" Type="Double" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter DbType="Date" Name="date" />
<asp:Parameter Name="reading" Type="Double" />
<asp:Parameter Name="price" Type="Double" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</div>
<div class="content-wrapper">
<dx:BootstrapChart runat="server" DataSourceID="Energy_ds" EncodeHtml="True" LoadingIndicatorText="" Palette="Office" TitleText="Monthly Reading">
<ValueAxisCollection>
<dx:BootstrapChartValueAxis Name="Reading" TitleText="Reading">
<TitleSettings Alignment="Center" Text="Reading">
</TitleSettings>
<VisualRangeSettings>
<DateAxis>
<MinLength Days="1" />
</DateAxis>
</VisualRangeSettings>
<Label>
<Format Type="Decimal" />
</Label>
</dx:BootstrapChartValueAxis>
</ValueAxisCollection>
<SeriesCollection>
<dx:BootstrapChartSeries ArgumentField="date" TagField="difference_next_reading" Type="Bar" ValueField="difference_next_reading">
<Aggregation Enabled="True" Method="Sum" />
<Label>
<ArgumentFormat Type="ShortDate" />
<Format Type="ShortDate" />
</Label>
</dx:BootstrapChartSeries>
<dx:BootstrapChartSeries ArgumentField="date" ValueField="reading">
</dx:BootstrapChartSeries>
</SeriesCollection>
<TitleSettings Text="Monthly Reading">
</TitleSettings>
<SettingsExport ProxyUrl=""></SettingsExport>
</dx:BootstrapChart>
</div>
<script src="scripts/frontUpdate.js"></script>
</asp:Content>
vb code
'Imports System.
Imports System.Data.SqlClient
Partial Class Default2
Inherits System.Web.UI.Page
`Dim constr As String = ConfigurationManager.ConnectionStrings("sundayConnectionString").ConnectionString`
`Dim con As New SqlConnection(constr)`
Protected Sub btn_submit_Click(sender As Object, e As EventArgs) Handles btn_submit.Click
Dim cmd As New SqlCommand("insert into meter_reading(date, reading) values (#date,reading)")
cmd.Parameters.AddWithValue("#date", [date].Value)
cmd.Parameters.AddWithValue("#reading", txt_reading.Text)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
'[date].Value = ""
'txt_reading.Text = ""
End Sub
End Class
I have checked for AutoPostBack Property of ASPxGridView but could not find any. I have no idea how to do it in JS. also I search online but could'nt find anything.
I used following line in my JS file but of no avail
ASPxGridView1.Postback();
It might seem foolish because I am new to this thing.
Ok, so we have some "data type grid" to display data.
Then we have some (2) text boxes, you enter some values, click button, save that data to the database.
At that point, then for the grid display to "update", you have to in code re-load the grid/table display.
I don't have your data and grid, but say a grid of some simple hotels:
So, we have this markup:
<label class="text-info">Enter New Hotel Name:</label>
<asp:TextBox ID="txtHotel" runat="server" Style="border-radius: 8px"></asp:TextBox>
<label class="text-info" style="margin-left: 20px">Enter New City:</label>
<asp:TextBox ID="txtCity" runat="server" Style="border-radius: 8px"></asp:TextBox>
<asp:Button ID="cmdAdd" runat="server" Text="Add (submit)" CssClass="btn" Style="margin-left: 12px" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" Width="40%"
AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table" GridLines="none">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescript" runat="server"
Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Ok, and code to load is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
End Sub
Sub LoadData()
Dim strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName"
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim rst As New DataTable
rst.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rst
GridView1.DataBind()
End Using
End Using
End Sub
Note VERY close - we ONLY load the grid on the first real page load, not each time a post-back occurs (so, ALWAYS for 99% of your pages, loading code goes in that if not IsPostback stub in page load).
Ok, so now we have this:
so, we can enter a new hotel name and city, and hit our submit button.
That button code will have two jobs:
Add/insert the data into database.
re-load the grid to show updated data (a new row).
So, that code will look near like what you have, but AFTER the insert of data, then we have to re-load the grid display.
so, then this code:
Protected Sub cmdAdd_Click(sender As Object, e As EventArgs)
Dim strSQL As String =
"INSERT INTO tblHotelsA (HotelName, City)
VALUES (#Hotel, #City)"
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
cmdSQL.Parameters.Add("#hotel", SqlDbType.NVarChar).Value = txtHotel.Text
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text
conn.Open()
cmdSQL.ExecuteNonQuery()
End Using
End Using
LoadData() '<----- re-load the grid
End Sub
So, the insert data code you have looks good. But right after you insert into the database, you need to re-load the data control (grid) you have.

Reading data from a grid view into text boxes vb

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

Populate gridview only on button click

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

Getting SQLDataSource Update Parameter from Gridview

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

Using Checkbox to Delete row in Gridview with Visual Basic.net code behind and Stored Procedures

Tools for my website:
Visual Studio 2010
SQL Management Studio
asp.net
visual basic.net
I am using GridView. Because of my search code I am not able to use the automatic delete function that GridView has to offer.
I clicked on GridView, said "Add New Column" and added a checkbox column.
I want to be able to check one or more boxes and select a button that will delete those rows from the database using a stored procedure.
Below is the ASP.net part of my code
Default.aspx
<%# Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ContactList._Default" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<%-- CONNECTION STRING--%>
<%--string Connection = "server=Local; uid=sa; pwd=; database=TGMInfo; Connect Timeout=10000";--%>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to THE TGM CONTACTS SITE</h2>
<p>
</p>
<p></p>
<center>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
Add a new record to the database<br />
<br />
<%--Text boxes for First Name, Last Name and Main Phone Number--%>
<asp:Label ID="lblFirstName" runat="server" Text="First Name:"></asp:Label>
<asp:TextBox ID="txtFirstName" runat="server" Width="160px"></asp:TextBox>
<asp:Label ID="LblLastName" runat="server" Text="Last Name:"></asp:Label>
<asp:TextBox ID="txtLastName" runat="server" Width="160px"></asp:TextBox>
<asp:Label ID="lblMainPhone" runat="server" Text="Main Phone #:"></asp:Label>
<asp:TextBox ID="txtMainPhone" runat="server" Width="160px"></asp:TextBox>
<asp:MaskedEditExtender ID="txtMainPhone_MaskedEditExtender" runat="server"
ErrorTooltipEnabled="True" Mask="(999) 999-9999" MaskType="Number"
TargetControlID="txtMainPhone">
</asp:MaskedEditExtender>
<br />
<br />
<%--Button adds information from the text fields to the SQL Database--%>
<asp:Button ID="btnAdd" runat="server" Text="Add Record" />
<br />
<br />
<br />
Search by Last Name<br />
<asp:Label ID="lblQuery" runat="server" Text="Last Name:"></asp:Label>
<asp:TextBox ID="txtQuery" runat="server" ToolTip="Search by last name"></asp:TextBox>
<br />
<br />
<asp:Button ID="BtnQuery" runat="server" Text="Search" />
<br />
</center>
<p>
</p>
<p>
</p>
<center>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="EmpId"
EmptyDataText="There are no data records to display." CellPadding="4"
ForeColor="#333333" GridLines="None" Height="136px" Width="299px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<%-- <asp:BoundField DataField="MainPhoneNumber" HeaderText="Main Phone Number"
SortExpression="MainPhoneNumber" />--%>
<asp:BoundField DataField="EmpId" HeaderText="EmpId" ReadOnly="True"
SortExpression="EmpId" Visible="False" />
<asp:BoundField DataField="FirstName" HeaderText="First Name"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name"
SortExpression="LastName" />
<asp:TemplateField HeaderText="Main Phone Number">
<ItemTemplate>
<asp:Literal ID="litPhone" runat="server" Text='<%# string.Format("{0:(###) ###-####}", Int64.Parse(Eval("MainPhoneNumber").ToString())) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Check For Deletion">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
<p>
<center>
<asp:Button ID="Button1" runat="server" Text="Delete Selected Rows"
ToolTip="Check desired rows and click this button for deletion" />
</p>
<p>
</p>
</center>
</asp:Content>
I think I posted everything that I need to, if not I can post more. I did not post the code-behind (visual basic.net) or the 2 stored procedures I have so far. I am very new to vb.net/asp.net/stored procedures.
Use this code for your delete method to scan your checkboxes and delete rows.
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each gvr As GridViewRow In GridView1.Rows
If gvr.Visible AndAlso DirectCast(gvr.FindControl("CheckBox1"), CheckBox).Checked Then
Response.Write(String.Format("DELETING ROW {0}<br>", gvr.DataItemIndex))
gvr.Visible = False 'Hide the row without the need for a re-bind'
'Use the "DataItemIndex" to get the database row key information for your delete'
'run your delete procedure'
End If
Next
End Sub
Here is my information for finding the checked checkboxes.
Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As EventArgs) Handles btnDelete.Click
'Create String Collection to store
'IDs of records to be deleted
Dim idCollection As New StringCollection()
Dim strID As String = String.Empty
'Loop through GridView rows to find checked rows
For d = 0 To GridView1.Rows.Count - 1
If GridView1.Rows(d).Cells.FromKey("DeleteRecord").Value = True Then
strID = GridView1.Rows(d).Cells.FromKey("EmpID").Value
idCollection.Add(strID)
End If
Next
'Call the method to Delete records
DeleteMultipleRecords(idCollection)
QueryEmployees("")
End Sub
Here is the code for the sub that calls my stored procedure.
Private Sub DeleteMultipleRecords(ByVal idCollection As StringCollection)
Dim SqlConn4 As SqlConnection = New SqlConnection("Password=;Persist Security Info=True;User ID=;Initial Catalog=;Data Source=.\SQLEXPRESS")
Dim cmd4 As New SqlCommand("Password=;Persist Security Info=True;User ID=;Initial Catalog=;Data Source=.\SQLEXPRESS")
Dim IDs As String = ""
For Each id As String In idCollection
IDs += id.ToString() & ","
Next
Try
'Dim strIDs As String = IDs.Substring(0, IDs.LastIndexOf(","))
'Dim strSql As String = "Delete from Details WHERE ID in (" & strIDs & ")"
For i = 0 To idCollection.Count - 1
cmd4.CommandType = CommandType.StoredProcedure
cmd4.Parameters.AddWithValue("#IDs", CInt(idCollection(i)))
cmd4.CommandText = "dbo.SPDeleteEmp"
cmd4.Connection = SqlConn4
SqlConn4.Open()
cmd4.ExecuteNonQuery()
Next
Catch ex As SqlException
Dim errorMsg As String = "Error in Deletion"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
SqlConn4.Close()
End Try
End Sub
While this works, at the moment this only deletes one checked box at a time, but does the bulk of what I needed to know. Also, thank you Carter for helping answer this question.

Resources