Update SSRS report parameters using custom ASP.NET controls - asp.net

I have a ASP.NET web app, which uses SSRS 2008 R2 on another machine in Native mode. The app has a page for generation reports created in SSRS.
I use my own custom controls for report parameters. After all the parameters are set, the page generates the report using a hidden ReportViewer control.
Here is the page layout:
<asp:Repeater ID="rptParameters" runat="server">
<ItemTemplate>
<tr>
<td class="label">
<asp:Literal ID="label" runat="server"/>:
</td>
<td class="control">
<asp:TextBox ID="tbx" runat="server" Visible="false"/>
<my:tsJCalendar ID="calendar" runat="server" GeneratePostback="false" HasValidation="true" ErrorDisplay="None" CompareMessage="Date must be in valid 'mm/dd/yyyy' format!" Visible="false"/>
<asp:RadioButtonList ID="radioList" runat="server" Visible="false"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem Text="True" Value="1"></asp:ListItem>
<asp:ListItem Text="False" Value="0"></asp:ListItem>
</asp:RadioButtonList>
<asp:DropDownList ID="ddl" runat="server" Visible="false"></asp:DropDownList>
<asp:HiddenField ID="hdnForDdl" runat="server"/>
</td>
<td width="22px"></td>
</ItemTemplate>
<AlternatingItemTemplate>
<td class="label">
<asp:Literal ID="label" runat="server"/>:
</td>
<td class="control">
<asp:TextBox ID="tbx" runat="server" Visible="false"/>
<my:tsJCalendar ID="calendar" runat="server" GeneratePostback="false" HasValidation="True" ErrorDisplay="None" CompareMessage="Date must be in valid 'mm/dd/yyyy' format!" Visible="false"/>
<asp:RadioButtonList ID="radioList" runat="server" Visible="false">
<asp:ListItem Text="True" Value="1"></asp:ListItem>
<asp:ListItem Text="False" Value="0"></asp:ListItem>
</asp:RadioButtonList>
<asp:DropDownList ID="ddl" runat="server" Visible="false"></asp:DropDownList>
<asp:HiddenField ID="hdnForDdl" runat="server"/>
</td>
</tr>
</AlternatingItemTemplate>
</asp:Repeater>
<rsweb:ReportViewer ID="rvReports" runat="server" Width="100%"
ShowReportBody="False" ShowPromptAreaButton="false" ShowWaitControlCancelLink="false"
AsyncRendering="false" Visible="false">
</rsweb:ReportViewer>
<hr />
<asp:Button ID="btnRun" runat="server" Text="Run Report" />
To generate custom parameter controls I use the repeater and show an appropriate control according by the report parameter type.
I am working with SSRS using its ReportingService2005 webservice. E.g. on the first page loading, I am getting report parameters using this code:
Private Function GetParameterReports(values As ParameterValue()) As ReportParameter()
Dim rs As New ReportingService2005()
rs.Credentials = New MyReportCredentials().NetworkCredentials
Dim forRendering As Boolean = True
Dim historyID As String = Nothing
Dim credentials As DataSourceCredentials() = Nothing
Dim paramInfos As ReportParameter() = rs.GetReportParameters(ReportPath, historyID, forRendering, values, credentials)
Return paramInfos
End Function
The 'values' parameter is Nothing for the first time. However, if a parameter depends on other parameters, I do a postback, and pass report values to the report to get updated parameters, using the same GetParameterReports() method.
All the reports have a special field, 'user_id', which is the identifier of the logged in user. I must set this parameter manually in the code, and I am trying to do this by using 2 ways:
Dim Values As New List(Of ParameterValue)()
Dim singleUserParameter As New ParameterValue()
With singleUserParameter
.Name = "user_id"
.Value = Security.CurrentUserPeopleID
End With
Values.Add(singleUserParameter)
paramInfos = GetParameterReports(Values.ToArray)
and
Dim userIdParameter As New ReportParameter()
userIdParameter.DefaultValues = New String() {Security.CurrentUserPeopleID.ToString()}
userIdParameter.PromptUser = False
Dim rs As New ReportingService2005()
rs.Credentials = New MyReportCredentials().NetworkCredentials
rs.SetReportParameters(ReportPath, paramInfos)
paramInfos = GetParameterReports(Nothing)
Some of the report parameters depend on the 'user_id', but, unfortunately, after calling ReportingService2005.GetReportParameters() with the passed 'user_id' value, dependent parameters still don't have DefaultValues.
Could you help to understand whether I am doing something wrong while setting the report parameters values, or the reason is in how the SSRS report was created?

Related

How to check for duplicate entries in a gridview and prevent them

I am relatively new to programming and I am having trouble figuring out how to detect and prevent a user from entering in duplicate values into a gridview I have containing multiple controls. Currently I am using a foreach loop to loop through the controls that contain the values that cannot be duplicates and it works for the most part, however when I edit the first record in a table and try to "update" the record, even if I haven't changed any values, I receive a null reference exception and I don't know why. I have attached any pertinent code below and would appreciate any and all help to come to a solution.
Please excuse the long post, I am trying to be as thorough as possible without adding irrelevant information.
To start I have a grid view with a series of controls in it allowing a user to enter information into our database. The gridview and the relevant controls can be seen below.
<asp:GridView ID="GridView2" runat="server"
EmptyDataText="No Miscellaneous" AutoGenerateColumns="False"
ShowHeaderWhenEmpty="True" DataKeyNames="RecID"
ShowFooter="True" DataSourceID="SqlDataSource7" Width="95%"
OnRowDataBound="OnRowDataBound" >
<EmptyDataTemplate>
<asp:DropDownList ID="ddlMiscEquipmentNew" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID"
DataTextField="EquipmentPart" AppendDataBoundItems="True" AutoPostBack="True" Width="220px" Height="20px" style="margin-left: 70px;" >
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlMiscNew" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description"
AppendDataBoundItems="true" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscNew_SelectedIndexChanged"
OnDataBound="ddlMiscNew_DataBinding">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtMiscQuantityNew" runat="server" Width="95px" Style="margin-left: 68px;" AutoPostBack="True" OnTextChanged="txtMiscQuantityNew_TextChanged" />
<asp:TextBox ID="txtMiscCostNew" runat="server" Width="95px" Text="0" ReadOnly="True" />
<asp:TextBox ID="txtMiscRequestedNew" runat="server" Width="95px" Text="0" ReadOnly="True" />
<asp:TextBox ID="txtMiscTaxNew" runat="server" Width="95px" Text="0" />
<asp:Button ID="InsertDetail" runat="server" CommandName="InsertDetail" Height="25px" Text="Add Detail" Width="85px" UseSubmitBehavior="True" />
</EmptyDataTemplate>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowEditButton="True" FooterText="Add -->" ShowDeleteButton="true" HeaderStyle-Width="70px" />
<asp:BoundField DataField="RecID" HeaderText="RecID" SortExpression="RecID" ReadOnly="True" Visible="False" />
<asp:TemplateField HeaderText="Miscellaneous" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label ID="lblMiscEquipmentAdd" Text='<%# Bind("EquipmentType") %>' runat="server" Width="220px" />
<asp:Label ID="lblMiscDescriptionAdd" Text='<%# Bind("MiscDescription") %>' runat="server" Width="220px" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlMiscEquipmentEdit" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID" DataTextField="EquipmentPart" SelectedValue='<%# Eval("EquipmentID") %>'
AppendDataBoundItems="True" AutoPostBack="True" Width="220px" Height="20px">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlMiscEdit" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description" SelectedValue='<%# Eval("MiscType") %>' AppendDataBoundItems="True" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscEdit_SelectedIndexChanged">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlMiscEquipmentInsert" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID" DataTextField="EquipmentPart"
AppendDataBoundItems="True" Width="220px" Height="20px" style="margin-left: 29px;">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlMiscInsert" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description" AppendDataBoundItems="True" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscInsert_SelectedIndexChanged">
<asp:ListItem Value="0">---SELECT---</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
There are more controls in the gridview but these are where the problem lies. As you can see there are a number of drop down lists and textboxes, the controls in question are the drop down list "ddlMiscEdit" in the edit item template and the label "lblMiscDescriptionAdd". When the user makes a selection in the aforementioned ddl and proceeds to hit the insert detail button at the end of each row it adds the values to the gridview, and in turn they are added to my database through a row command event. This works as intended, the problem I run into is when a user trys to edit the first row of the gridview and changes the value for ddlMiscEdit, it triggers a null reference exception for the label lblMiscDescriptionAdd.
In order to detect duplicates I have a For Each loop in the selectedIndexChanged event for the ddlMiscEdit drop down as shown below.
For Each row In GridView2.Rows
Dim miscdescription As Label = (CType(row.FindControl("lblMiscDescriptionAdd"), Label))
If miscdescription.Text = ddlMiscEdit.SelectedItem.Text Then
lblErrorMisc.Text = "Miscellaneous items can only be claimed once"
Return
Else
lblErrorMisc.Text = ""
Return
End If
Next
I am thinking this exception has to do with the fact that when the user clicks edit it activates the drop down list and hides the label, thus when it comes to the loop "lblMiscDescriptionAdd" doesn't exist in that specific context.
I have also tried putting the foreach loop in the row command event for the gridview in the "Update" commandName section, which leads to the same issue but in a different place. When this loop is in the Update section mentioned above, instead of receiving this exception on the first record of the gridview I receive it in the second/third/fourth record, basically everything except the first record.
I use that same foreach loop in the InsertDetail command and it works as intended preventing duplicate values from being entered into the gridview, the exception only appears when I am trying to edit a given row depending on where I put the loop.
I apologize for the long post but I don't really know how to simplify my issue beyond what I have done here. I am pretty new to programming so I don't know if I could go about doing this in a better/more efficient manner, but any help/critiques would be greatly appreciated as I am at a loss as to how to fix this problem. Thank you in advance for any effort on your part for helping me solve this.
To make a long story short?
Don't try and process the GV.What happens if other users are adding data. You may well not have re-loaded the grid with updated data.
In your save code for the one record, simple hit/pull/query the main database and check for the record. That way you not messing around all day trying to process and pull values out of the GV.
Always try to think in terms of data management, not trying to use the actual GV as some kind of database - it only for display, and selecting the data to edit, but to check for duplicates, then simple query the database for that information and check if such records already exist.
For example, I have a simple GV with some hotels. (that working example you can try here: http://www.kallal.ca/Website11/WebForm2 ).
So, I have a add button to allow adding of a new reocrd. And I also have a "save" button. It would be in that save button that I simple add code to check say if the hotel name already exists in the database, and not allow that addition.
And what happens with edits? If a user edits existing, and again changes a name to some existing value, then again you have to deal with code to test/check that case.
So, be it adding, or editing, you need to check for that duplicate.
The code thus becomes rather simple. My save button code thus with code to check for the hotel already existing could/would look/work like this:
Protected Sub cmdSave_ServerClick(sender As Object, e As EventArgs)
' check for dupliate hotel name when saving or adding new reocrd.
Dim intPK As Integer = ViewState("PK")
Dim strSQL As String =
"SELECT HotelName FROM tblHotelsA
WHERE HotelName = #HotelName AND ID <> #ID"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#HotelName", SqlDbType.NVarChar).Value = txtHotel.Text
cmdSQL.Parameters.Add("#ID", SqlDbType.NVarChar).Value = intPK
Dim rstDataCheck As DataTable = MyrstP(cmdSQL)
If rstDataCheck.Rows.Count > 0 Then
' we have a duplicate hotel, don't allow adding!
' code here to inform user that this is a duplicate
' hotel and you can't add it.
Me.MyCustomMessage.InnerText = "Can't add this hotel - duplicate"
Exit Sub
End If
' code here to save the edit back to database
strSQL = "SELECT * FROM tblHotelsA WHERE ID = " & intPK
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL2 = New SqlCommand(strSQL, conn)
conn.Open()
Dim da As New SqlDataAdapter(cmdSQL2)
Dim daU As New SqlCommandBuilder(da)
Dim rstData As New DataTable
rstData.Load(cmdSQL2.ExecuteReader)
With rstData.Rows(0)
.Item("HotelName") = txtHotel.Text
.Item("FirstName") = tFN.Text
.Item("LastName") = tLN.Text
.Item("City") = tCity.Text
.Item("Province") = tProvince.Text
.Item("Description") = txtNotes.Text
.Item("Active") = chkActive.Checked
.Item("Balcony") = chkBalcony.Checked
.Item("Smoking") = chkSmoking.Checked
End With
da.Update(rstData)
End Using
End Using
LoadGrid() ' refrsh grid to show any new edits
ShowGrid(True) ' hide edit area, show grid
End Sub
So, in action, then the above will look like this.
We will edit the record and try to create a duplicate.

Using TextBox TextChanged event to enable or disable a button control in asp.net

I am using an asp TextBox control with its TextChanged event and my goal is to capture text as a user enters it. If there are one or more characters entered, I would like a button control to be enabled without the user having to leave the TextBox control.
My source code for the TextBox on the aspx page is
<asp:TextBox ID="NewSpendingCategoryTextBox" MaxLength="12" runat="server"
AutoPostBack="True"
OnTextChanged="NewSpendingCategoryTextBox_TextChanged"
ViewStateMode="Enabled" >
</asp:TextBox>
and my source code on the code behind page is
Protected Sub NewSpendingCategoryTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles NewSpendingCategoryTextBox.TextChanged
Dim strSpendingCategoryTextBox As String = Nothing
strSpendingCategoryTextBox = NewSpendingCategoryTextBox.Text
If strSpendingCategoryTextBox.Length <= 0 Then
Me.NewSpendingCategoryInsertButton.Enabled = False
Else 'strSpendingCategoryTextBox.Length > 0
Me.NewSpendingCategoryInsertButton.Enabled = True
End If 'strSpendingCategoryTextBox.Length <= 0
End Sub
So it appears I have to use javascript to enable or disable the insert button. Can someone guide me on how to get an element within a table? The table sits in a Panel as well.
below is the aspx code...
<asp:Panel ID="AddSpendingCategoryPanel" Visible="false" runat="server">
<table class="AddNewTable">
<tbody>
<tr>
<td>
<asp:Label ID="lblSpend" runat="server"
Text="Spending Category:">
</asp:Label>
</td>
<td>
<asp:TextBox ID="txtSpend" MaxLength="12"
runat="server"
AutoPostBack="True"
OnTextChanged="txtSpend_TextChanged"
OnKeyDown="return CheckSpendTextBoxValue()"
ViewStateMode="Enabled" >
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button CssClass="frmbtn" ID="btnInsertSpend"
runat="server" Text="Insert" />
</td>
<td>
<asp:Button CssClass="frmbtn" ID="btnCancelSpend"
runat="server" Text="Cancel"
CausesValidation="False" />
</td>
</tr>
</tbody>
</table>
</asp:Panel>
Run this code in the OnKeyPress event or consider JavaScript. The textbox does not fire the Text_Changed event til Tab or Enter are used.
Simplify the boolean check.
Me.NewSpendingCategoryInsertButton.Enabled = (NewSpendingCategoryTextBox.Text.Length <> 0)
I'm not sure exactly how you would do it. But the ASP.NET code is executed on the server that is hosting the web page.
I'd highly recommended doing it on JavaScript which can be run client side. Hopefully this article is of use to you.
How to check if a textbox is empty using javascript

how to pass ID value from one page to another

I have three hyperlinks in my table.
These hyperlinks are used for the print preview of the crystal reports.
The problem is the selected content of the print preview of the crystal report should be equal to the ID from the other page.
here is the code behind, this page will be responsible for the passing and redirecting of the ID
Sub OnFinishButtonClick(ByVal sender As Object, ByVal e As WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
If Wizard1.ActiveStepIndex = 6 Then
''au1.regau1()
ElseIf Wizard1.ActiveStepIndex = 7 Then
'au2.regau2()
End If
Response.Redirect("~/operator/renewInstruction.aspx")
End Sub
and this is the other page.
Here is my hyperlink in table:
<table class="req">
<tr class="field_value3">
<td><asp:Label ID="req3" runat="server" Text="A. Affidavit of Undertaking(FVO shall comply with the requirements of R.A. 8550)" ></asp:Label></td><td>
<asp:HyperLink ID="au8550_h4" runat="server" ForeColor ="blue" Target="_Blank"><asp:Image ID="Image3" runat="server" ImageUrl ="~/images/preview.png" Height="25px" Width="30px" ImageAlign="AbsMiddle"/></asp:HyperLink></td>
</tr>
<tr class="field_value4">
<td><asp:Label ID="req4" runat="server" Text="B. Affidavit of Undertaking to the effect that the FVO shall comply with FAQ No. 232 (applicable only to fishing vessels which intend to operate in Manila Bay)" ></asp:Label></td><td>
<asp:Hyperlink ID="au232_h3" runat="server" Target="_blank" ForeColor ="Blue" ><asp:Image ID="Image4" runat="server" ImageUrl ="~/images/preview.png" Height="25px" Width="30px" ImageAlign="AbsMiddle"/></asp:Hyperlink></td>
</tr>
<tr class="field_value5">
<td><asp:Label ID="req5" runat="server" Text="C. Certification to the effect that the fishing vessel is not involved in any administrative or judicial case" ></asp:Label></td><td>
<asp:HyperLink ID="Cert_h5" runat="server" Target ="_blank" ForeColor ="blue"><asp:Image ID="Image5" runat="server" ImageUrl ="~/images/preview.png" Height="25px" Width="30px" ImageAlign="AbsMiddle"/></asp:HyperLink></td>
</tr>
</table>
here is the code behind for the hyperlink:
au232_h3.NavigateUrl = "~/operator/printAU232.aspx?Au232VesselID=" & Session("vid")
au8550_h4.NavigateUrl = "~/operator/printAu8550.aspx?Au8550VesselID=" & Session("vid")
Cert_h5.NavigateUrl = "~/operator/printCERT.aspx?CertVesselID=" & Session("vid")
how will i able to pass the value of vid to the other page so that it will be the unique basis for the selection of the print preview content of the crystal report.

Do a Button Click from Code behide

I have a gridview which lists Tools and Access values. To edit I have an edit imagebutton on each row. I have an OnRowBound method which assigns an OnClick attribute to each button so that I will know which record I need to edit.
The code is
Protected Sub ChangeFirstRowIcon(ByVal Sender As Object, ByVal e As GridViewRowEventArgs) Handles gv_AccessRights.RowDataBound
'This sub fires on each gridview row created...
'It first checks that the row is a data row (as opposed to Header, Footer etc.)
'If ib_Edit is true then change add an attribut to button with aid, tid and ac values attached.
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ib_Edit As ImageButton = e.Row.FindControl("ib_Edit")
Dim lb_AccessID As Label = e.Row.FindControl("lb_AccessID")
Dim hd_ToolID As HiddenField = e.Row.FindControl("hd_ToolID")
Dim hd_AccessCode As HiddenField = e.Row.FindControl("hd_AccessCode")
If ib_Edit IsNot Nothing Then
ib_Edit.Attributes.Add("onClick", "proxyClick('" & lb_AccessID.Text & "', '" & hd_ToolID.Value & "', '" & hd_AccessCode.Value & "')")
End If
End If
End Sub
I'm using a hidden proxy button to show a modal popup which the user will use to edit a record... (the same popup will be used to add a new access record... but that will come later). So having passed my details to proxyClick I set values to controls within the modal popup. The javascript is....
<script type="text/javascript">
function proxyClick(aid, tid, ac) {
document.getElementById('hd_AccessID').value = aid;
document.getElementById('hd_ToolIDMod').value = tid;
document.getElementById('hd_AccessCodeMod').value = ac;
document.getElementById('but_SetModalDetails').click();
}
</script>
For reference the main bits of the markup are....
<table class="border">
<tr>
<td>
<asp:Button ID="but_SetModalDetails" runat="server" Style="display: none" Text="Set modal details" ClientIDMode="Static" UseSubmitBehavior="true" />
<asp:Button ID="but_HiddenProxy" runat="server" Style="display: none" Text="Hidden Proxy Button for Modal Popup" ClientIDMode="Static" />
</td>
<td class="rt">
<asp:Button ID="but_AddTool" runat="server" AccessKey="A" CssClass="butGreen" Text="Add Tool" ToolTip="Add Tool - Alt A" />
</td>
</tr>
</table>
<asp:ModalPopupExtender ID="mpx_AddEditAccess" runat="server" CancelControlID="but_Cancel"
BehaviorID="pn_AddEditAccess" PopupControlID="pn_AddEditAccess" TargetControlID="but_HiddenProxy"
BackgroundCssClass="modalBackground" />
<asp:Panel ID="pn_AddEditAccess" runat="server" Width="500px" CssClass="modalPopup"
Style="display: block">
<div class="box">
<h2>
<asp:Label ID="lb_ModTitle" runat="server"></asp:Label>
</h2>
<asp:HiddenField ID="hd_AccessID" runat="server" ClientIDMode="Static"></asp:HiddenField>
<div class="block">
<asp:UpdatePanel ID="up_Access" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl_ToolName" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<th class="p66 rt">
Tool Name:
</th>
<td class="p66">
<asp:HiddenField ID="hd_ToolIDMod" runat="server" ClientIDMode="Static" />
<asp:DropDownList ID="ddl_ToolName" runat="server" AutoPostBack="true" AppendDataBoundItems="True"
DataSourceID="SqlDS_Tools" DataTextField="ToolName" DataValueField="ToolID" OnSelectedIndexChanged="ddl_ToolName_SIC">
<asp:ListItem Text="Please Select..." Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDS_Tools" runat="server" ConnectionString="<%$ ConnectionStrings:ToolsConnString %>"
SelectCommand="SELECT [ToolID], [ToolName] FROM [tbl_Tools] WHERE ([Redundant] = #Redundant)">
<SelectParameters>
<asp:Parameter DefaultValue="False" Name="Redundant" Type="Boolean" />
</SelectParameters>
</asp:SqlDataSource>
<asp:RequiredFieldValidator ID="rfv_ddl_ToolName" runat="server" ControlToValidate="ddl_ToolName"
CssClass="error" Display="Dynamic" ErrorMessage="Please Select Tool Name" InitialValue="0">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<th class="p66 rt">
Access Rights:
</th>
<td class="p66">
<asp:HiddenField ID="hd_AccessCodeMod" runat="server" ClientIDMode="Static" />
<asp:DropDownList ID="ddl_AccessCode" runat="server" Enabled="false">
<asp:ListItem Text="No Access" Value="0"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="p66">
<asp:Button ID="but_Cancel" runat="server" Text="Cancel" />
</td>
<td class="p66 rt">
<asp:Button ID="but_Save" runat="server" Text="Save" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</asp:Panel>
As you can see I have implemented two hidden buttons but_SetModalDetails and but_HiddenProxy. but_SetModalDetails has some codebehind which sets a couple of dropdown lists (one populated from a datasource, the other is populated dynamically based on the value of the first. The codebehind is...
Protected Sub but_SetModalDetails_Click(ByVal sender As Object, ByVal e As EventArgs) Handles but_SetModalDetails.Click
If hd_AccessID.Value = "0" Then
lb_ModTitle.Text = "Assigning Access Rights to:"
ddl_ToolName.SelectedIndex = 0
ddl_AccessCode.SelectedIndex = 0
ddl_AccessCode.Enabled = False
Else
lb_ModTitle.Text = "Edit Access Rights to:"
ddl_ToolName.SelectedValue = hd_ToolIDMod.Value
ddl_ToolName.Enabled = False
SqlStr = "SELECT AccessID AS ddlValue, AccessText as ddlText FROM tbl_AccessCodes WHERE ToolID = " & hd_ToolIDMod.Value
PopulateDDLvalue(ddl_AccessCode, SqlStr)
ddl_AccessCode.SelectedValue = hd_AccessCodeMod.Value
ddl_AccessCode.Enabled = True
End If
'NOW I NEED TO SIMULATE but_HiddenProxy Click
End Sub
As you can see at the end I need to simulate a click of but_HiddenProxy so that the modalPopup is shown populated with the correct data.
Any Ideas? Thanks
After all that... I was able to do everything in codebehind...
I only needed one hidden button but_HiddenProxy.
In the gridview instead of setting an onClick attribute for each edit image button I just set a commandname of 'AccessEdit' (don't use 'Edit'). I then had a method that handled the gridview.RowCommand event. This found the various info I needed by using findControl on the selected row. These values were then used to populate the dropdowns in the popup and then use the show command to make the popup visible.
One bit that did stump me for a while was why my RowCommand was not triggering when an imagebutton was clicked. I'd forgotten that I had validation in the modal which stopped the RowCommand being executed. I stuck a CausesValidation="false" in the imagebutton and all was OK.
Talk about using a hammer to crack a nut!

GridView isn't reflecting AJAX changes

I'm using AJAX right now to update my GridView when I search for a string of text in the gridview, or when I select from a dropdownlist what I want to order the Gridview by. This was working previously, but I had really messy code. So I've cleaned it up a little bit, added some parameters and such. Unfortunately, now, when the selectedindex of the dropdownlist is changed or when someone tries to search for a field, nothing happens - the page just refreshes. I'm also getting an exception saying "The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name".
If you need to see any more code then please let me know!
public vieworders()
{
this.PreInit += new EventHandler(vieworders_PreInit);
}
void vieworders_PreInit(object sender, EventArgs e)
{
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
updateDatabase(fieldString, orderByString);
}
protected void updateDatabase(string _searchString, string _orderByString)
{
string updateCommand = "SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE #searchString OR lName LIKE #searchString OR zip LIKE #searchString OR email LIKE #searchString OR cwaSource LIKE #searchString OR length LIKE #searchString OR price LIKE #searchString ORDER BY #orderByString";
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Cabot3");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
// Create an SqlConnection to the database.
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
using (SqlCommand _fillDatabase = new SqlCommand(updateCommand, connection))
{
connection.Open();
_fillDatabase.Parameters.Add("#searchString", SqlDbType.VarChar, 50).Value = _searchString;
_fillDatabase.Parameters.Add("#orderByString", SqlDbType.VarChar, 50).Value = _orderByString;
_fillDatabase.ExecuteNonQuery();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
// create the DataSet
dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
Form
<form id="form1" runat="server">
<asp:ScriptManager ID = "ScriptManager" runat="server" />
<div>
<asp:Label runat="server" id = "orderByLabel" Text = "Order By: " />
<asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<ContentTemplate>
<div style= "overflow:auto; height:50%; width:100%">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "IdentityColumn"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" AutoPostBack = "true" Checked ='<%#Eval("processed") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
<div style= "overflow:auto; height:50%; width:100%" />
<table border="1">
<tr>
<td>Name: </td>
<td><%=name %></td>
</tr>
<tr>
<td>Zip: </td>
<td><%=zip %></td>
</tr>
<tr>
<td>Email: </td>
<td><%=email %></td>
</tr>
<tr>
<td>Length: </td>
<td><%=length %></td>
</tr>
<tr>
<td>Price: </td>
<td><%=price %></td>
</tr>
<tr>
<td>Source: </td>
<td><%=source %></td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I have never used the UpdatePanel since my company uses Telerik, but from the examples I see during my research I remember seeing a trigger component.
From my understanding, if the control is w/i the UpdatePanel itself, then you do not have to specify the trigger, since it is assumed.
For your scenario, the trigger (dropdownlist) is outside of the UpdatePanel. You may need to include this in your aspx:
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="orderByList" >
</Triggers>
<ContentTemplate>
...
Try the following:
In HTML move the update panel direct after the scriptmanager line.
Move the code lines in vieworders_PreInit to vieworders_PageLoad with !IsPostPack clause.

Resources