Why won't my UpdatePanel update my Listbox as I expect on button click? - asp.net

I have a form with a dropdownlist, two buttons, and two Listboxes inside an UpdatePanel. The Dropdownlist, and listboxes are all bound to SqlDatasources. The dropdownlist allows you to choose your department.
The first listbox shows a list of Jobs associated with what you've selected from the department.
The second listbox shows an inverse list of those items. (Jobs in the database that are not associated with your department)
When an item is removed from the 1st listbox, it should show up in the 2nd listbox. When an item is removed from the 2nd listbox, it should show up in the 1st listbox.
This functionality allows you to add and remove jobs from your department
The are two buttons on the page function as Add and Remove buttons. Everything is working except the Listboxes will not reliably update. The Data itself is updated in the database, and if I refresh (F5) it will show correctly.
<asp:ScriptManager ID="smgrDeptsJobs" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="uPanelDeptsJobs" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlDepartments" runat="server"
DataSourceID="sqldsDepartments" DataTextField="Department"
DataValueField="DeptID" Width="150px" AutoPostBack="True">
</asp:DropDownList>
<asp:ListBox ID="lstJobsIn" runat="server" DataSourceID="sqldsJobsIn"
DataTextField="JobName" DataValueField="JobID" height="156px"
width="220px">
</asp:ListBox>
<asp:Button ID="btnAddJob" runat="server" Text="<<" Width="70px"
CausesValidation="False" />
<asp:Button ID="btnRemoveJob" runat="server" Text=">>" Width="70px"
CausesValidation="False" />
<asp:ListBox ID="lstJobsOut" runat="server" DataSourceID="sqldsJobsOut"
DataTextField="JobName" DataValueField="JobID" height="156px"
width="220px">
</asp:ListBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlDepartments"
EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="btnAddJob" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnRemoveJob" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
The code for the two button click events is below:
Protected Sub btnAddJob_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddJob.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdInsert As SqlCommand = sqlJobsDB.CreateCommand()
sqlJobsDB.Open()
sqlCmdInsert.CommandText = _
"INSERT INTO tblDeptsJobs (DeptID, JobID) VALUES " + _
"(#DeptID, #JobID)"
' Declare the data types for the parameters
sqlCmdInsert.Parameters.Add("#DeptID", SqlDbType.TinyInt)
sqlCmdInsert.Parameters.Add("#JobID", SqlDbType.TinyInt)
' Assign the parameters values from the form
sqlCmdInsert.Parameters("#DeptID").Value = ddlDepartments.SelectedValue
sqlCmdInsert.Parameters("#JobID").Value = lstJobsOut.SelectedValue
' Execute the insert Statement
sqlCmdInsert.ExecuteNonQuery()
sqlJobsDB.Close()
End Sub
Protected Sub btnRemoveJob_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemoveJob.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdDelete As SqlCommand = sqlJobsDB.CreateCommand()
sqlJobsDB.Open()
sqlCmdDelete.CommandText = _
"DELETE FROM tblDeptsJobs WHERE tblDeptsJobs.DeptID = #DeptID AND tblDeptsJobs.JobID = #JobID"
' Declare the data types for the parameters
sqlCmdDelete.Parameters.Add("#DeptID", SqlDbType.TinyInt)
sqlCmdDelete.Parameters.Add("#JobID", SqlDbType.TinyInt)
' Assign the parameters values from the form
sqlCmdDelete.Parameters("#DeptID").Value = ddlDepartments.SelectedValue
sqlCmdDelete.Parameters("#JobID").Value = lstJobsIn.SelectedValue
' Execute the insert Statement
sqlCmdDelete.ExecuteNonQuery()
sqlJobsDB.Close()
End Sub
It feels like when I add or remove a job, the listbox that I last selected an item in, is the one that doesn't update.
I also can't get the dropdownlist to update the listboxes without setting autopostback on the dropdownlist to True.
The ugly Band-Aid fix I've come up with is using the listbox.items.clear() method and then rebinding the data for each listbox.

Basically what is happening is that you update your database but never rebind your controls. I'm not sure exactly what you will have to put into your click handlers to make this work (because I have never used the SQL datasource controls before), but it should look something like this:
Protected Sub btnAddJob_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddJob.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdInsert As SqlCommand = sqlJobsDB.CreateCommand()
sqlJobsDB.Open()
sqlCmdInsert.CommandText = _
"INSERT INTO tblDeptsJobs (DeptID, JobID) VALUES " + _
"(#DeptID, #JobID)"
' Declare the data types for the parameters
sqlCmdInsert.Parameters.Add("#DeptID", SqlDbType.TinyInt)
sqlCmdInsert.Parameters.Add("#JobID", SqlDbType.TinyInt)
' Assign the parameters values from the form
sqlCmdInsert.Parameters("#DeptID").Value = ddlDepartments.SelectedValue
sqlCmdInsert.Parameters("#JobID").Value = lstJobsOut.SelectedValue
' Execute the insert Statement
sqlCmdInsert.ExecuteNonQuery()
sqlJobsDB.Close()
//may need to do explicit call to DB to get data here
//after you have the data, rebind
lstJobsIn.DataBind();
lstJobsOut.DataBind();
End Sub
That's roughly what it will look like. I would be interested to see what exactly you do to solve your problem.

Just set dropdownlist autopostback to true, remove all triggers and set ChildrenAsTriggers="true" on the updatepanel.

Related

How do I assign OnRowCommand to multiple IDs ASP.net and VB.net Backend

I have 2 GridViews with separate IDs
I need the backend code to update the one being viewed when a button is clicked.
` Protected Sub savestatus(sender As Object, e As EventArgs)
Dim btn As Button = TryCast(sender, Button)
Dim row As GridViewRow = CType(((CType(sender, Button)).NamingContainer), GridViewRow)
Dim rowindex As Integer = row.RowIndex
Dim code As String = GridView1.DataKeys(row.RowIndex).Values(0).ToString()
Dim type As Int32 = GridView1.DataKeys(row.RowIndex).Values(1)
Dim statusid As Integer
Dim checkLocked, checkerror As CheckBox
' For Each row As GridViewRow In GridView1.Rows
checkLocked = CType(GridView1.Rows(rowindex).FindControl("lock"), CheckBox)
checkerror = CType(GridView1.Rows(rowindex).FindControl("error"), CheckBox)
If checkerror.Checked Then ' error
statusid = 2
End If
If checkLocked.Checked Then
statusid = 3
End If`
How do I make the GridView1 a variable depending on which grid view the button is pressed in.
Ok, it would have helped a lot to at least show the button and a few rows of the gridview markup.
There are about 10 ways to do this. (really !!!).
However, in your case, two check boxes, and you need actions to occur when a check box is changed – AND say change the other one!!
Now I am using two check boxes – but it could be a text box or whatever I change.
So, say I have this grid markup
Some columns + TWO un-bound check boxes.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:TemplateField HeaderText="Good">
<ItemTemplate>
<asp:CheckBox ID="chkGood" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkGood_CheckedChanged"
MyRowID ='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bad">
<ItemTemplate>
<asp:CheckBox ID="chkBad" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkBad_CheckedChanged"
MyRowID ='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Ok, and now the code to load the grid:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
Using cmdSQL As New SqlCommand("SELECT ID, HotelName, City, Province from tblHotels",
New SqlConnection(My.Settings.Test3))
cmdSQL.Connection.Open()
GridView1.DataSource = cmdSQL.ExecuteReader
GridView1.DataBind()
End Using
End If
End Sub
And thus we have this:
Ok, so far - very simple.
Now note CLOSE at the markup for the two check boxes.
And while dropping a button or whatever on a normal form - you can then double click to JUMP to the code behind event/stub?
Well, for buttons or whatever you drop INSIDE of a grid, you can't double click on the control to create + jump to the code behind stub.
But, WHILE in the markup, you can start typing the event, and you get this:
Note VERY careful how the intel-sense pops up a option to create the event. So click on that option. Nothing seems to happen, but NOW we get a code stub behind.
So, we have this code stub for the chkOk event:
Protected Sub chkGood_CheckedChanged(sender As Object, e As EventArgs)
Dim ckBox As CheckBox = sender
Dim RowID As Integer = ckBox.Attributes.Item("MyRowID")
Dim gvRow As GridViewRow = GridView1.Rows(RowID)
If ckBox.Checked = True Then
' do whatever if true - say un-check the "bad" check box
Dim ckBoxBad As CheckBox = gvRow.FindControl("chkBad")
ckBoxBad.Checked = False
Else
' code here if the user just un-checked the "good" check box
End If
End Sub
Note a few things:
We pick up the button click - then shove it into a checkbox control. This is just a lot easier to get the check box value, and our CUSTOM MyRowID
(and this works if it was a button for example).
We then get the custom made up Attribute we added called "MyRowID"
MyRowID ='<%# Container.DataItemIndex %>'
You can see the expression in the Markup - it passes the current row id. Sometimes, I'll pass other values from the row and you can do this like this:
<asp:CheckBox ID="chkBad" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkBad_CheckedChanged"
MyRowID ='<%# Container.DataItemIndex %>'
MyPKID = '<%# Eval("ID") %>' />
So in above, I pass both RowID and a custom MyPKID (so the Eval() expression can be used to pass any valid data row avaialble at binding time. Its often handy then having to grab and mess with a data row - you JUST grab the button from sender - and you don't care about gridview or anything else to get a few extra values. (just a FYI tip). So for example, I REALLY don't want the PK row id as the first row. So I could remove it and STILL use the above idea to PASS the pk row id - all columns can be used - even if a control is NOT in the grid - as long as the column exists during the data binding process - you can grab it.
So, now we pick up the current GridRow - and we are free to modify whatever we want on that row.
In my simple example, we pick up the OTHER check box - and un-check if it was checked. But we could say update other things on that row.
And I did the same for the chkBad check box. And I have really the same as the first chkBox code stub. Eg this:
Protected Sub chkBad_CheckedChanged(sender As Object, e As EventArgs)
Dim ckBox As CheckBox = sender
Dim RowID As Integer = ckBox.Attributes.Item("MyRowID")
Dim gvRow As GridViewRow = GridView1.Rows(RowID)
If ckBox.Checked = True Then
' user checked the bad box, un-check the good one
Dim ckBoxGood As CheckBox = gvRow.FindControl("chkGood")
ckBoxGood.Checked = False
Else
' code here if the user just un-checked the "bad" check box
End If
End Sub
So in above we just hard right past the GridView bult in events.
So in above, if you check one box and the other is checked - we un-check it. Needless to say, I would use a button list, or a checkbox list, and that above code would of course then not be required. But it still a good example on how to pluck/get the current row. And then get/pluck controls from that row.
Note that for the first 3 rows (the databound), you can NOT use findControl, and they are referenced using the gvRow.Cells(0) (starting at 0 to N columns. So no findcontrol is required for these databound columns or autogenerated ones. They do NOT have a name - you have to use number starting at 0 in the cells collection. Of course for "templated" controls that we added as per above? Then you do in fact use findcontrol as per above.

VB.Net "logger" asp:Table and asp:UpdatePanel dynamic asynchronous update

I am writing a web page in ASP.Net. Presently, I have an asp:Table that I am using as a sort of "log" for processing output. The idea is that the user selects several files and clicks a button, and each file is "processed" with the log showing what is happening. Processing occurs asynchronously.
Here is the relevant processing segment:
Protected Sub DoAsyncWork()
Dim count = 0
For Each row As GridViewRow In gvList.Rows
count = count + 1
If CType(row.FindControl("cbImport"), System.Web.UI.WebControls.CheckBox).Checked Then
push_to_log("")
push_to_log("Updating Active Projects +" + HttpUtility.HtmlDecode(row.Cells(1).Text).ToString.Substring(0, 30) + "...")
Dim xp(3) As Object
xp(0) = HttpUtility.HtmlDecode(row.Cells(0).Text)
xp(1) = HttpUtility.HtmlDecode(row.Cells(1).Text)
xp(2) = HttpUtility.HtmlDecode(row.Cells(2).Text)
xp(3) = 0
'oDC.UpdateData("Import_P3e_Project ", xp)
If (xp(3) <> 0) Then
push_to_log("Success: " + xp(3).ToString + " have been updated")
Else
push_to_log("Failure: " + xp(3).ToString + " activities updated")
End If
End If
Next
push_to_log("")
push_to_log("Import Complete!")
End Sub
This is how I am calling the process worker function:
Protected Sub button_Import(sender As Object, e As EventArgs) Handles btnImport.Click
Dim t As New Thread(New ThreadStart(AddressOf DoAsyncWork))
t.Priority = Threading.ThreadPriority.Normal
t.Start()
push_to_log("Start Import")
End Sub
The way I am appending things to the log is by dynamically creating rows and cells, then adding them to my table. Here is the relevant subroutine:
Protected Sub push_to_log(ByVal str As String)
Dim newRow As TableRow = New TableRow
Dim newCell As TableCell = New TableCell
logArrayList.Add(str)
Me.ViewState.Add("arrayListInViewState", logArrayList)
newCell.Text = str
newCell.Style("Color") = "White"
newCell.ID = "cell" + (logArrayList.Count - 1).ToString
newRow.ID = "row" + (logArrayList.Count - 1).ToString
newRow.Cells.Add(newCell)
logTable.Rows.Add(newRow)
HiddenButton_Click(HiddenButton, New EventArgs())
'UpdateLogPanel.Update()
'UpdateLogPanel.Focus()
End Sub
I've got the log persisting correctly by using the ViewState to store my arraylist of data and recreating the log on postbacks. The relevant markup for my log looks like this:
<asp:UpdatePanel ID="UpdateLogPanel" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="HiddenButton" />
</Triggers>
<ContentTemplate>
<div ID="Div1" class="DefinitionPanel" style="text-align:left;height:200px;overflow:hidden;" runat="server">
<span style="display:inline-block; width:100px;"></span>
<div class="scrollingtable">
<div>
<div id="viewContainer">
<asp:table id="logTable" runat="server" enableviewstate="false">
</asp:table>
</div>
</div>
</div>
</div>
<asp:Button ID="HiddenButton" runat="server" style="display:none;" />
</ContentTemplate>
</asp:UpdatePanel>
I am trying to make my asp:Table update every time a message is posted to it. I thought that enabling partial postbacks and using an UpdatePanel would be the correct solution, but my log still does not output anything until the entire process has completed.
After I add a message to my asp:Table/log, I tried calling
UpdateLogPanel.Update()
which didn't seem to make a difference. Finally I tried adding the asp:AsyncPostBackTrigger and hidden button with the hope that it would fix things but it doesn't seem to. Here is what the hiddenButton event looks like:
Protected Sub HiddenButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles HiddenButton.Click
UpdateLogPanel.Visible = True
End Sub
Any guidance on how to make my log re-render itself when I add a message to it would be highly regarded.
I chose to implement using pooling instead of an asynchronous method.
I still use an asp:UpdatePanel. Instead of a table inside of the UpdatePanel, I am now using a gridview, and a timer. When the timer fires, I rebind the gridview, thereby showing any new contents
The key components to making this work:
Square things away with the parent update panel and master page:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
'set reference to master site page
mstr = CType(Master, Site)
'setup partial rendering so Log can update asynchronously
scriptManager = CType(mstr.FindControl("ScriptManager1"), ScriptManager)
scriptManager.EnablePartialRendering = True
scriptManager.AsyncPostBackTimeout = 28800
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).UpdateMode = UpdatePanelUpdateMode.Conditional
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).ChildrenAsTriggers = False
End Sub
The mark-up for the UpdatePanel looks like
<asp:UpdatePanel ID="UpdateLogPanel" UpdateMode="Conditional"
RenderMode="Inline" ChildrenAsTriggers="false" runat="server">
<ContentTemplate>
<%--The Gridview and other Hidden Fields--%>
<asp:Timer ID="myTimer" OnTick="timer_tick" runat="server" Interval="1000" Enabled="false"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myTimer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
Triggering the logging mechanism is done simply by setting
myTimer.Enabled = True
The timer_tick event looks like
Public Sub timer_tick(ByVal sender As Object, ByVal e As EventArgs)
generate_log()
//other logging logic (increment counters, "timeout" mechanism)
UpdateLogPanel.Update()
End Sub

How to clear exisiting dropdownlist items when its content changes?

ddl2 populates based on ddl1 selected value successfully.
My issue is the data that is already present in ddl2 does not clear before appending the new data so ddl2 content just continues to grow every time ddl1 is changed.
<asp:DropDownList ID="ddl1" RunAt="Server" DataSourceID="sql1" DataValueField="ID1" DataTextField="Name2" AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Text="ALL" Selected="True" Value="0"/>
</asp:DropDownList>
<asp:DropDownList ID="ddl2" RunAt="Server" DataSourceID="sql2" DataValueField="ID2" DataTextField="Name2" AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Text="ALL" Selected="True" Value="0"/>
</asp:DropDownList>
<asp:SqlDataSource ID="sql1" RunAt="Server" SelectCommand="sp1" SelectCommandType="StoredProcedure"/>
<asp:SqlDataSource ID="sql2" RunAt="Server" SelectCommand="sp2" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Type="Int32" Name="ID1" ControlID="ddl1" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>
I have tried re-databinding in code behind on selected index change and also items.clear with little success.
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
ddl2.Items.Clear()
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
QUESTION
How to get items present in an asp:dropdownlist to clear before new values are populated when the dropdownlists content is dependent on another dropdownlists selected value?
Please post any code in VB
Using ddl.Items.Clear() will clear the dropdownlist however you must be sure that your dropdownlist is not set to:
AppendDataBoundItems="True"
This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.
SOLUTION
Add AppendDataBoundItems="False" to your dropdownlist.
Now when data is rebound it will automatically clear all existing data beforehand.
Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.
TOP TIP
Still want a default list item adding to your dropdown but need to rebind data?
Use AppendDataBoundItems="False" to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.
ddl.Items.Insert(0, New ListItem("Select ...", ""))
You should clear out your listbbox prior to binding:
Me.ddl2.Items.Clear()
' now set datasource and bind
Please use the following
ddlCity.Items.Clear();
Just 2 simple steps to solve your issue
First of all check AppendDataBoundItems property and make it assign false
Secondly clear all the items using property .clear()
{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}
just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal
e As EventArgs)
//ddl2.Items.Clear()
ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub
and it worked just fine

Refresh ListBox control during a loop

Using ASP.NET and VB.NET code behind, I have the following code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim I As Integer = 0
For I = 0 To 10
ListBox1.Items.Add(I)
ListBox1.DataBind()
System.Threading.Thread.Sleep(300)
Next
End Sub
The intended output of the code is to update the listbox1 control at each iteration, but what really happens is it updates the listbox1 control after the entire loop finishes..
Is there a way to update the listbox1 control as its intended by the code logic?
You need to place the ListBox inside UpdatePanel and trigger the Button1_Click event as as Async; Something like this:
<asp:UpdatePanel runat="server" ID="pnlUpdate">
<ContentTemplate>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
This should work accordingly:
Dim I As Integer = 0
For I = 0 To 10
ListBox1.Items.Add(I)
Next
If you debug then you'll see with each iteration an item is added to Items of ListBox1 control but the effect only be visible if the page/form is loaded.

GridView Row Redirect to Pre-filled DetailsView on Button Click

Background:
I have a GridView which gets populated from an SqlDataSource via DataSourceID. The rows show some summary data from an SQL View. Upon clicking a row, I would like to take my user to another page with a DetailsView control which gets populated with the full set of values from the DB related to the row clicked. My user should be able to edit the data, download files associated with the record, and create a new record of a different type based on said data.
Error:
All examples that I've found for Clickable GridView rows end up with some variation of the error Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
Naturally, I do not want to expose my site to vulnerabilities by disabling event validation. I need to be able to grab the Primary key of the clicked row's associated record and perform operations on that data on a subsequent page, probably via a DetailsView. I suspect my errors are a result of my setup, which is why I included those details.
My Questions Are:
How do I capture the Primary Key of clicked row?
How do I, onclick, forward to a "details" page with a pre-filled form containing data from the row record that was clicked?
HERE'S THE COMPLETE SOLUTION
**thanks again to Icarus' help
'Fetch the DataKey ("ID"), seems to work
Protected Sub RowBind(ByVal sender As Object, ByVal e As GridViewRowEventArgs) _
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim datakey As String = GridView1.DataKeys(e.Row.RowIndex).Value.ToString()
End If
End Sub
'Handle button click
Protected Sub RowClick(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) _
Handles GridView1.RowCommand
If e.CommandName = "Select" Then
'Add to session variable; translate the index of clicked to Primary Key
Session.Add("DetailsKey", GridView1.DataKeys(e.CommandArgument).Value.ToString)
Response.Redirect("details.aspx")
End If
End Sub
And My Markup
<asp:GridView ID="GridView1" runat="server" DataSourceID="GridView1SDS"
DataKeyNames="ID" AllowPaging="True" AllowSorting="True">
'<!-- Styling -->
<Columns>
<asp:ButtonField ButtonType="Button" Text="Details" CommandName="Select" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="GridView1SDS" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
SelectCommand="select * from viewRequestQueue">'<!-- An SQL View -->
</asp:SqlDataSource>
Forwarded Page VB & Markup
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GridView2SDS.SelectCommand = "select * from viewRequestQueue where ID = " _
+ Session.Item("DetailsKey").ToString
End If
End Sub
<asp:DetailsView ID="GridView2" runat="server" DataSourceID="GridView2SDS">
'<!-- Styling -->
</asp:DetailsView>
<asp:SqlDataSource ID="GridView2SDS" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>">
</asp:SqlDataSource>
Also, please note that if the SelectCommand for your DataSource is handled in the codebehind, that means the DataBind will overwrite your <Columns> in the markup. To get around this, you should define the columns in the code behind before the DataBind. So say I wanted to add another ButtonField column to my forwarded page (notice the SelectCommand is not provided in the markup), I added the following before the setting the SelectCommand and doing the DataBind:
Dim id As New ButtonField()
id.ButtonType = ButtonType.Button
id.Text = "Load"
id.CommandName = "Select"
PubDetails.Columns.Add(id)
You need to declare the KeyNames of the items you are binding on your markup. For example:
<asp:GridView id="grid" runat="Server" DataSourceID="YourSQLDataSource" DataKeyNames="ID,Name" />
In your case, you seemed to be handling the OnRowDataBound event. You can do this to grab the key inside RowBound:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim datakey As String = GridView1.DataKeys(e.Row.RowIndex).Value.ToString() 'get the datakey
End If
Your second question is difficult to answer because you did not specify how you want the user to be redirected, if from the client side using Javascript or from the Server side. You also did not specify how do you expect to populate the details on the Details page. Do you expect to read a parameter from the URL and use it to get the record details from the database?

Resources