Reading data from a grid view into text boxes vb - asp.net

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>

Related

Stored Procedure not working with bulk update to rows bound to gridview

I'm using a grid view to update all rows in the grid at the same time. This code is working on another page perfectly. The difference now is that I'm calling a stored procedure since I have 3 tables I need to update. I receive no errors but nothing is getting updated in the tables. I believe that the parameters are not getting passed through properly.
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="False" DataKeyNames="CUST_ORDER_ID">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="CUST_ORDER_ID" HeaderText="ORDER_ID" SortExpression="CUST_ORDER_ID">
<ItemStyle Width="50px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="NAME" HeaderText="NAME" ReadOnly="True" SortExpression="NAME">
<ItemStyle Width="400px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ORDERDATE" HeaderText="ORDER DATE" DataFormatString="{0:d}" ReadOnly="True" SortExpression="ORDERDATE">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="DESIREDSHIPDATE" HeaderText="DESIRED SHIP DATE" SortExpression="DESIREDSHIPDATE" DataFormatString="{0:d}" ReadOnly="True" ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="PROMISEDATE" HeaderText="PROMISE DATE" SortExpression="PROMISEDATE" DataFormatString="{0:d}" ReadOnly="True" ItemStyle-Width="100">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="PROMISEDELDATE" HeaderText="DELIVERY DATE" SortExpression="PROMISEDELDATE" DataFormatString="{0:d}" ReadOnly="True" ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="TRIP_ORDER" SortExpression="TRIP_ORDER" ItemStyle-Width="500">
<EditItemTemplate>
<asp:textbox ID="TextBox3" runat="server" Text='<%# Bind("TRIP_ORDER") %>'></asp:textbox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TripOrderTextBox" runat="server" Text='<%# Bind("TRIP_ORDER") %>' Width="25px"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="25px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="ORDER_LINE_SUMMARY" HeaderText="ORDER LINE SUMMARY" SortExpression="ORDER_LINE_SUMMARY">
<ItemStyle Width="50px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="JOB_DEL_NOTES" SortExpression="JOB_DEL_NOTES" ItemStyle-Width="500">
<EditItemTemplate>
<asp:textbox ID="TextBox1" runat="server" Text='<%# Bind("JOB_DEL_NOTES") %>'></asp:textbox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="JobDelNotesTextBox" runat="server" Text='<%# Bind("JOB_DEL_NOTES") %>' Rows="3" TextMode="MultiLine" Width="500px" onkeypress="return this.value.length<=79" MaxLength="80"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="500px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="ORDER_DEL_NOTES" SortExpression="ORDER_DEL_NOTES" ItemStyle-Width="500">
<EditItemTemplate>
<asp:textbox ID="TextBox2" runat="server" Text='<%# Bind("ORDER_DEL_NOTES") %>'></asp:textbox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="OrderDelNotesTextBox" runat="server" Text='<%# Bind("ORDER_DEL_NOTES") %>' Rows="3" TextMode="MultiLine" Width="500px" onkeypress="return this.value.length<=79" MaxLength="80"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="500px"></ItemStyle>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:ConnectionStringTest %>"
ProviderName="<%$ ConnectionStrings:ConnectionStringTest.ProviderName %>"
SelectCommandType="StoredProcedure" SelectCommand="CM_GET_SCHEDULED_ORDERS"
UpdateCommandType="StoredProcedure" UpdateCommand="CM_SP_UPDATE_TRIP">
<SelectParameters>
<asp:QueryStringParameter Name="DELIVERY_DATE" DbType="DateTime" Direction="Input" QueryStringField="PROMISE_DEL_DATE" DefaultValue="" />
<asp:Parameter Name="UPDATE_TRIP" DefaultValue="YES" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="CUST_ORDER_ID" DefaultValue="" Type="String" Direction="Input" />
<asp:Parameter Name="ORDER_LINE_SUMMARY" Type="String" Direction="Input" />
<asp:Parameter Name="TRIP_ORDER" DefaultValue="" Type="String" Direction="Input"/>
<asp:Parameter Name="PROMISEDELDATE" Defaultvalue="" Type="datetime" Direction="Input"/>
<asp:Parameter Name="JOB_DEL_NOTES" Type="String" Direction="Input"/>
<asp:Parameter Name="ORDER_DEL_NOTES" Type="String" Direction="Input"/>
</UpdateParameters>
</asp:SqlDataSource>
My code behind:
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Public Class UpdateTrip
Inherits System.Web.UI.Page
Private tableCopied As Boolean = False
Private originalDataTable As System.Data.DataTable
Protected Sub Page_load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
SetDateTextBox.Text = Request.QueryString("PROMISE_DEL_DATE")
End If
End Sub
Protected Sub btnRedirect_Click(sender As Object, e As EventArgs)
Response.Redirect("~/UpdateTrip.aspx?PROMISE_DEL_DATE=" + SetDateTextBox.Text)
End Sub
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If Not tableCopied Then
originalDataTable = CType(e.Row.DataItem, System.Data.DataRowView).Row.Table.Copy()
ViewState("originalValuesDataTable") = originalDataTable
tableCopied = True
End If
End If
End Sub
Protected Sub UpdateButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles UpdateTrip.Click
originalDataTable = CType(ViewState("originalValuesDataTable"), System.Data.DataTable)
For Each r As GridViewRow In GridView1.Rows
'If IsRowModified(r) Then GridView1.UpdateRow(r.RowIndex, False)
GridView1.UpdateRow(r.RowIndex, False)
Next
' Rebind the Grid to repopulate the original values table.
'tableCopied = False
'GridView1.DataBind()
Response.Redirect("~/UpdateTrip.aspx?PROMISE_DEL_DATE=" + SetDateTextBox.Text)
End Sub
'Protected Function IsRowModified(ByVal r As GridViewRow) As Boolean
' Dim currentID As String
' Dim currentTripOrder As String
' Dim currentJobDelNotes As String
' Dim currentOrderDelNotes As String
' currentID = Convert.ToInt32(GridView1.DataKeys(r.RowIndex).Value)
' currentTripOrder = CType(r.FindControl("TripOrderTextBox"), TextBox).Text
' currentJobDelNotes = CType(r.FindControl("JobDelNotesTextBox"), TextBox).Text
' currentOrderDelNotes = CType(r.FindControl("OrderDelNotesTextBox"), TextBox).Text
' Dim row As System.Data.DataRow =
' originalDataTable.Select(String.Format("cust_order_id = {0}", currentID))(0)
' If Not currentTripOrder.Equals(row("Trip_order").ToString()) Then Return True
' If Not currentJobDelNotes.Equals(row("Job_Del_Notes").ToString()) Then Return True
' If Not currentOrderDelNotes.Equals(row("Order_Del_Notes").ToString()) Then Return True
' Return False
'End Function
Protected Sub Calendar1_SelectionChanged(sender As Object, e As EventArgs) Handles Calendar1.SelectionChanged
SetDateTextBox_PopupControlExtender.Commit(Calendar1.SelectedDate)
End Sub
End Class
Stored Procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Michael Mueller>
-- Create date: <8/3/2016>
-- Description: <update multiple tables for the trip order. customer_order. cust_order_line, cust_address>
-- =============================================
ALTER PROCEDURE [dbo].[CM_SP_UPDATE_TRIP]
-- Add the parameters for the stored procedure here
#CUST_ORDER_ID varchar(15),
#ORDER_LINE_SUMMARY VARCHAR(MAX),
#TRIP_ORDER VARCHAR(3),
#PROMISE_DEL_DATE DATETIME,
#JOB_DEL_NOTES varchar(80),
#ORDER_DEL_NOTES VARCHAR(80)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- update cust_adress with job delivery notes
UPDATE CUST_ADDRESS
SET USER_4 = #JOB_DEL_NOTES
FROM dbo.CUSTOMER_ORDER INNER JOIN
dbo.CUST_ADDRESS ON dbo.CUSTOMER_ORDER.CUSTOMER_ID = dbo.CUST_ADDRESS.CUSTOMER_ID AND
dbo.CUSTOMER_ORDER.SHIPTO_ID = dbo.CUST_ADDRESS.SHIPTO_ID
WHERE (dbo.CUSTOMER_ORDER.ID = #CUST_ORDER_ID)
-- update customer_order with order delivery notes
UPDATE CUSTOMER_ORDER
SET USER_5 = #ORDER_DEL_NOTES
WHERE ID = #CUST_ORDER_ID
-- update cust_order_line with trip_order information
IF #ORDER_LINE_SUMMARY = 'ALL LINES'
BEGIN
UPDATE CUST_ORDER_LINE
SET USER_4 = #TRIP_ORDER
WHERE CUST_ORDER_ID = #CUST_ORDER_ID
END
ELSE -- ONLY SPECIFIC LINES OF ORDER GET UPDATED
BEGIN
UPDATE CUST_ORDER_LINE
SET USER_4 = #TRIP_ORDER
WHERE CUST_ORDER_ID = #CUST_ORDER_ID AND PROMISE_DEL_DATE = #PROMISE_DEL_DATE
END
I figured out the main problem. Using Sql Server Profile I could see that only the binding fields are getting passed to the stored procedure. The other values were null. I created ItemTemplates for the remaining parameters.

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.

Must declare the scalar variable error when inserting into Gridview

My webpage consist of a GridView, which allows the user to view, edit, and insert data. The data is inserted using a DetailView-Form, which opens via a javaScript-type window. One of the columns in the GridView consist of a company_guid, which is captured via a session that is setup in a log-in page. I'm attempting to capture the user's company_guid and log it into the Grid upon inserting data. I'm able to view and edit the Gridview, but I get the following error when I try to insert: Must declare the scalar variable "#companyguid".
The following is my Hypertext - GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Part_ID" DataSourceID="SqlDataSource1"
AutoGenerateEditButton="True" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="Part_ID" HeaderText="Part_ID"
SortExpression="Part_ID" InsertVisible="False" ReadOnly="True" Visible="false" />
<asp:BoundField DataField="Company_guid" HeaderText="Company_guid"
SortExpression="Company_guid" Visible="false" />
<asp:BoundField DataField="Part_Name" HeaderText="Part_Name"
SortExpression="Part_Name" />
<asp:BoundField DataField="Part_Desc" HeaderText="Part_Desc"
SortExpression="Part_Desc" />
<asp:CheckBoxField DataField="Active" HeaderText="Active"
SortExpression="Active" />
<asp:BoundField DataField="UpdateDate" HeaderText="UpdateDate"
SortExpression="UpdateDate" />
<asp:BoundField DataField="UpdateBy" HeaderText="UpdateBy"
SortExpression="UpdateBy" />
</Columns>
</asp:GridView>
The Detail View (this is what opens via the JavaScript Window):
<asp:DetailsView
id="dtlCarrier"
DataSourceID="SqlDataSource1"
AutoGenerateInsertButton="True"
AutoGenerateRows="False"
DefaultMode="Insert"
Runat="server" DataKeyNames="Part_ID">
<Fields>
<asp:BoundField DataField="Part_Name" HeaderText="Part_Name"
SortExpression="Part_Name" />
<asp:BoundField DataField="Part_Desc" HeaderText="Part_Desc"
SortExpression="Part_Desc" />
<asp:CheckBoxField
DataField="Active"
HeaderText="Active" SortExpression="Active" />
<asp:BoundField DataField="UpdateDate" HeaderText="UpdateDate"
SortExpression="UpdateDate" />
<asp:BoundField DataField="UpdateBy" HeaderText="UpdateBy"
SortExpression="UpdateBy" />
</Fields>
</asp:DetailsView>
<!-- the sql data source -->
<asp:SqlDataSource
ID="SqlDataSource1"
ConnectionString="<%$ ConnectionStrings:ShipperNotificationConnectionString %>"
SelectCommand="SELECT * FROM [Part]"
UpdateCommand="UPDATE Part SET Part_Name=#Part_Name,
Part_Desc=#Part_Desc, Active=#Active, UpdateDate=#UpdateDate, UpdateBy=#UpdateBy
WHERE Part_ID=#Part_ID"
InsertCommand="INSERT Part (company_guid,Part_Name,Part_Desc,Active,UpdateDate,UpdateBy)
VALUES (#companyguid,#Part_Name,#Part_Desc,#Active,#UpdateDate,#UpdateBy)"
runat="server"
/>
The code behind:
Public Class SupplierPartsMgmt
Inherits System.Web.UI.Page
'Globally declare my variable to hold the company_guid
Dim companyGuid As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'initialized companyGuid to the session varible, which is capured/stored via the log-in pg
If Not Page.IsPostBack Then
companyGuid = Session("numrecord").ToString
Else
companyGuid = Session("numrecord").ToString
End If
End Sub
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
'Dim companyGuid As String = ""
If Not String.IsNullOrEmpty(companyGuid) Then
SqlDataSource1.InsertParameters.Add("companyguid", companyGuid)
SqlDataSource1.Insert()
End If
End Sub
End Class
Could I please get some help as to what I'm doing wrong?
Drop the # in this line:
SqlDataSource1.InsertParameters.Add("companyguid", companyGuid)
# is only needed while writing the query to indicate query parameters.
And if you still need the #, i think you need to declare the <InsertParameters> elements under your asp:SqlDataSource element.
Option #1
You could declare a session based insert parameter directly as follows:
<InsertParameters>
<asp:SessionParameter Name="companyguid" SessionField="companyguid" Type="String" />
</InsertParameters>
Option #2
You can also set the company guid parameter value in the oninserting command as follows:
<InsertParameters>
<asp:Parameter Name="companyguid" Type="String" />
</InsertParameters>
OnInserting="On_Inserting" - add this attribute to your SQL Data Source
protected void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["#companyguid"].Value = valueFromSession;
}

selected gridview, populate a gridview with a nested gridview. doesnt work. helppp

I have 3 gridviews
1st gridview enable selection, which will populate the 2nd gridview if it has any data.
while the 3rd gridview is nested inside the 2nd gridview.
However, the 3rd gridview never ever show any single data..
What am i missing?
I can achieve this if the 2nd gridview is populated on the page load.
here is the code
im on asp.net c#
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="SurveyID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="SurveyID" HeaderText="SurveyID"
SortExpression="SurveyID" />
<asp:BoundField DataField="SurveyTitle" HeaderText="SurveyTitle"
SortExpression="SurveyTitle" />
<asp:CommandField ShowSelectButton="True" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
SelectCommand="SELECT [SurveyID], [SurveyTitle] FROM [Survey]">
</asp:SqlDataSource>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="QuestionID" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="QuestionID" HeaderText="QuestionID"
InsertVisible="False" ReadOnly="True" SortExpression="QuestionID" />
<asp:BoundField DataField="QuestionTitle" HeaderText="QuestionTitle"
SortExpression="QuestionTitle" />
<asp:BoundField DataField="AnswerType" HeaderText="AnswerType"
SortExpression="AnswerType" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" DataKeyNames="ResultID">
<Columns>
<asp:BoundField DataField="ResultID" HeaderText="ResultID"
SortExpression="ResultID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="QuestionID" HeaderText="QuestionID"
SortExpression="QuestionID" />
<asp:BoundField DataField="AnswerValue" HeaderText="AnswerValue"
SortExpression="AnswerValue" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
SelectCommand="SELECT * FROM [Results] WHERE ([QuestionID] = #QuestionID)">
<SelectParameters>
<asp:Parameter Name="QuestionID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
SelectCommand="SELECT [QuestionID], [QuestionTitle], [AnswerType] FROM [Question] WHERE ([SurveyID] = #SurveyID)">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="SurveyID"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
You have to set AutoPostBack="True" on GridView1, so that it posts back if the user selected a row. But I'm not familiar with SqlDataSource. So i would set GridView2's DataSource property in the SelectedIndexChanged handler and then DataBind it.
If you want to bind the data to the inner's grid when GridView2 is bound, you should handle the RowDataBound event of GridView2, find the inner grid there, set it's datasource and databind it.
void GridView2_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var rowView = (DataRowView)e.Row.DataItem;
var GridView3 = (GridView)e.Row.FindControl("GridView3");
//set it's DataSource according to this row's DataItem
}
}

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

Resources