LinqDataSource - filtering for null values - asp.net

I am writing an ASP.Net web application. I have listview, it's datasource is a LinqDataSource. In my database, I have a staff table and I am trying filter for records by their team using a dropdownlist. This works fine, until I select "All" in the dropdownlist. It returns all staff except for the ones where the teamID is null. How can I return the records where teamID is null?
This is my code:
<asp:ListView ID="ListView1" runat="server" DataSourceID="ldsStaff" DataKeyNames="staffID">
<LayoutTemplate>
<table>
<tr>
<th>Name</th>
<th>Team</th>
</tr>
<tr>
<td>&nbsp</td>
<td><asp:DropDownList ID="ddlTeamFilter" runat="server" DataSourceID="ldsTeams" DataTextField="Team" DataValueField="TeamID" AppendDataBoundItems="true" AutoPostBack="true">
<asp:ListItem Text="[All]" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr ID="itemPlaceHolder" runat="server"></tr>
</table>
</LayoutTemplate>
....
</asp:Listview>
<asp:LinqDataSource ID="ldsStaff" runat="server"
ContextTypeName="ProjectDatabase.ProjectDatabaseUsersDataContext" OrderBy="name"
TableName="Staffs" EnableUpdate="True" Where="inService == #inService && TeamID == #TeamID">
<WhereParameters>
<asp:Parameter DefaultValue="true" Name="inService" Type="Boolean" />
<asp:ControlParameter ControlID="ctl00$ContentPlaceHolder1$ListView1$ddlTeamFilter" Name="TeamID" Type="Int32" PropertyName="SelectedValue"/>
</WhereParameters>
</asp:LinqDataSource>
In my code behind I handle the LinqDataSource selecting event:
Private Sub ldsStaff_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LinqDataSourceSelectEventArgs) Handles ldsStaff.Selecting
Dim ddl As DropDownList = CType(ListView1.FindControlRecursive("ddlTeamFilter"), DropDownList)
If ddl.SelectedValue = "" Then
e.WhereParameters.Remove("TeamID")
End If
I thought that if I removed the whereparameter when the dropdownlist is "All" it would force it to return all the records, but it doesn't work.
Please help!
Thanks,
Emma

If you are handling the selecting event anyway I would remove the Where clause in your datasource all together and handle everything in the selecting event setting the e.Result value to your linq query.
Then in your ddlTeamFilter rebind the listview on change.
Hope this helps.

Related

Report error, value cannot be null

I am stymied by the above error.
I have a report with a parameter called loc.
The intended purpose of the report is to allow users to select a location from the dropdownlist and then records associated with that location are displayed to the users.
The dropdownlist is getting populated with values just fine.
However, when I select a location from the dropdownlist, I get an error that says:
Value cannot be null. Parameter name: reportParameters
Everything works fine when I pass a value as textbox but not as dropdown.
Any ideas what I am doing wrong?
Below are relevant code. Please forgive me in advance for posting a lot of code.
'---Dropdownlist control
<asp:Panel runat="server" ID="pnlLoc" Font-Names="Calibri" BorderStyle="Solid" BorderWidth="1" Style="margin: 0 auto; width:300px;">
<table>
<tr>
<td>
<asp:Label runat="server" ID="lblLoc" Text="Location: " />
</td>
<td>
<asp:DropDownList runat="server" ID="ddLoc" DataSourceID="dslocator6" AutoPostBack="True">
</asp:DropDownList>
</td>
</tr>
</table>
</asp:Panel
--Report viewer control
<rsweb:ReportViewer ID="ReportViewer1" runat="server" AsyncRendering="true" SizeToReportContent="true" Font-Names="Arial"
Height="675px" Width="750px">
<LocalReport EnableExternalImages="true" ReportPath="">
</LocalReport>
</rsweb:ReportViewer></center>
<asp:ObjectDataSource ID="LOC" runat="server" SelectMethod="GetData" TypeName="ManageReportsTableAdapters.searchBylocationsTableAdapter">
<SelectParameters>
<asp:ControlParameter ControlID="ddLoc" Name="Location" DefaultValue=" " />
</SelectParameters>
</asp:ObjectDataSource>
--This code populates the ddLoc dropdownlist
Protected Sub btnLoc_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLoc.Click
ReportViewer1.LocalReport.ReportPath = ""
pnlLoc.Visible = True
which.Value = "P"
dslocator6.SelectCommand = "SELECT location FROM Locations ORDER BY [location]"
ddLoc.DataTextField = "location"
ddLoc.DataValueField = "location"
End Sub
'Define report parameter
Dim params(0) As ReportParameter
ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("locs", LOC.ID))
ReportViewer1.LocalReport.ReportPath = "locations.rdlc"
ReportViewer1.LocalReport.Refresh()
If Not String.IsNullOrEmpty(ddLoc.SelectedValue) Then
params(0) = New ReportParameter("loc", ddLoc.SelectedValue)
Else
params(0) = New ReportParameter("loc", sel, False)
End If
ReportViewer1.LocalReport.SetParameters(params) '<-- error points to this line
I was getting this error and the problem was me setting an extra index in my array
Dim params(2) As ReportParameter
params(0) = New ReportParameter("SignatureImg", "SomeBase64StringHere")
params(1) = New ReportParameter("SignatureImgMimeType", "image/png")
ReportViewer1.LocalReport.SetParameters(params)
Because of I defined my array like this Dim params(2) As ReportParameter and i was just adding values for the first two index the value on index 3 was null and it was creating the problem.
The solution was just defined the array like this Dim params(1) As ReportParameter.

Formview cascading dropdown issue

I'm working on a Formview where in the EditTemplate, I have 1 dropdownlist dependent on another dropdownlist value.
I've looked at some examples and have found this one to be the most concise and I am working off of it:
http://mikepope.com/blog/AddComment.aspx?blogid=1629
It's pretty straight-forward but it's not working for my ddl. Can you tell me what I am missing or not implementing properly? I have removed some of the code in order to troubleshoot but still, nothing. For example, I am not setting the selectedValue as nothing is being returned...
Any advice would be appreciated.
Thanks
HTML:
<EditItemTemplate>
...
...
...
<tr>
<td colspan="6" align="left">
<asp:DropDownList ID="ddTeams" runat="server" CssClass="myDropDownIndent" DataSourceID="sqlGetTeams" DataTextField="Team" DataValueField="Team" SelectedValue='<%# DetermineTeamValue(Eval("Team")) %>' AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged">
</asp:DropDownList>
</td>
<td colspan="4" align="left">
<asp:DropDownList ID="DropDownOwner" runat="server" CssClass="myDropDown" DataSourceID="sqlGetMembers2" DataTextField="EmployeeName" DataValueField="EmployeeName" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="sqlGetMembers2" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectDashboardConnectionString %>"
SelectCommand="usp_GetMembers" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="Type" />
<asp:Parameter Name="TeamID" />
</SelectParameters>
</asp:SqlDataSource>
</td>
</tr>
Code Behind:
Protected Sub fvTask_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles fvTask.DataBound
If fvTask.CurrentMode = FormViewMode.Edit Then
Dim dv As System.Data.DataRowView = fvTask.DataItem
Dim ddTeams2 As DropDownList = fvTask.FindControl("ddTeams")
Dim DropDownOwner As DropDownList = fvTask.FindControl("DropDownOwner")
Dim a As String = "A"
Dim dsc As SqlDataSource = fvTask.FindControl("sqlGetMembers2")
dsc.SelectParameters("TeamID").DefaultValue = String.Empty
dsc.SelectParameters("Type").DefaultValue = String.Empty
DropDownOwner.DataBind()
'If Not IsDBNull(dv("EmployeeName")) Then
' DropDownOwner.SelectedValue = dv("EmployeeName")
'End If
End If
Catch ex As Exception
ErrMessage = ex.ToString
End Try
End Sub
So, my 2nd dropdownlist is null.

how to fill listview cell with value from detailsview

I would like to know if is it possible to retrieve the value from a ddlist (Id) and assign it to a cell/ textbox of a listview?
I have 3 controls, ddl, detailsview, and listview on the web page.
The ddl controls the record that is displayed on the detailsview and the listview.
I would like to have the Recipe Id in the listview, to the id of the record selected in the ddl or the record id of the detailsview.
The 3 controls use entitydatasource to get the data.
Thank you greatly.
some code I tried without success was to have a sub running on the databound of the listview:
Protected Sub lvRecipeSteps_ItemDataBound(sender As Object, e As ListViewItemEventArgs) Handles lvRecipeSteps.DataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim dataItem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
If dataItem.DisplayIndex = lvRecipeSteps.EditIndex Then
Dim tb__1 As TextBox = TryCast(e.Item.FindControl("Recipe_IdTextBox"), TextBox)
End If
End If
End Sub
I get this error:
Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.ListViewItemEventArgs'
===========================================
This is the entitydatasource that the listview uses:
<asp:EntityDataSource
ID="EntityDataSource_RecipeSteps"
runat="server"
ConnectionString="name=OLTPEntities"
DefaultContainerName="OLTPEntities"
EnableFlattening="False"
EntitySetName="RefineRecipeStep"
Where="it.Recipe_Id = #RecipeID"
EnableDelete="True"
EnableInsert="True"
EnableUpdate="True"
EntityTypeFilter="RefineRecipeStep"
OrderBy="it.ProcessType, it.AdditionOrder">
<WhereParameters>
<asp:ControlParameter ControlID="ddRecipeItemNumber" DbType="Int32" Name="RecipeID" PropertyName="SelectedValue" />
</WhereParameters>
This is the field I am trying to have filled with the Id from the ddl, or detailsview:
<td class="RefineRecipe_Steps_Cells">
<asp:TextBox
ID="Recipe_IdTextBox"
runat="server"
Text='<%# Bind("Recipe_Id") %>' />
<asp:CustomValidator
ID="CustomValidator_Recipe_Id"
runat="server"
ErrorMessage="Enter numbers only, please"
ControlToValidate="Recipe_IdTextBox"
OnServerValidate="ServerValidation_IsNumber"
CssClass="cssCustomValidator"
Display="Dynamic">Digits only, please</asp:CustomValidator>
<asp:RequiredFieldValidator
ID="ReqField_RecipeId"
runat="server"
ErrorMessage="* Required"
ControlToValidate="Recipe_IdTextBox"
CssClass="cssCustomValidator"
Display="Dynamic">* Required</asp:RequiredFieldValidator>
</td>
Please any advice on how to do this would be much appreciated.
Thank you very much.

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!

How to get Selected Value in FormView Control?

I'm working with an application develop by ASP.NET, the problem I face is using FormView control, the FormView Control has ItemTemplate, InsertItemTemplate and EditItemTemplate.
Below is the code fragment of InsertItemTemplate:
<asp:FormView ID="FormView1" runat="server" DefaultMode="ReadOnly">
<InsertItemTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:Label id="lblPS" runat="server" Text="Process Status"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlPS" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label id="lblAP" runat="server" Text="Action Plan"></asp:Label>
</td>
<td>
<asp:TextBox id="txtAP" runat="server" Width="230px" TextMode="MultiLine" Rows="5"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</InsertItemTemplate>
</asp:FormView>
In Page_Load event, I do DataSource Binding into the DropDownList as below:
FormView1.ChangeMode(FormViewMode.Insert);
DropDownList ddlPS = FormView1.FindControl("ddlPS") as DropDownList;
ddlPS.DataSource=GetProcessStatus();
ddlPS.DataBind();
ddlPS.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- Please Select -", "- Please Select -"));
The data binding into DropDownList and the "- Please Select -" was ok.
Here the problem comes, when Submit Button click, I wanted to get user selected DropDownList Value, but the DropDownList.SelectedItem.Text always return me "- Please Select -".
Please advise how can I get the user selected value in InsertItemTemplate.
The problem is with your DataBind on Page Load event.
When you DataBind you clear the existing values and hence loose the selected value.
A drop down list remembers the items in it, so you don't need to DataBind on every postback.
Your could should be like this.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DropDownList ddlPS = FormView1.FindControl("ddlPS") as DropDownList;
ddlPS.DataSource=GetProcessStatus();
ddlPS.DataBind();
ddlPS.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- Please Select -", "- Please Select -"));
}
}

Resources