I'm in Asp.net 3.5 (Visual Studio 2008, VB). In a DetailsView, I've got several controls that need to perform hide/display actions, and I'm using an Update Panel. The first control is a radio button ("rblAttemptType") with two options: Phone Call or Letter. If the user chooses Phone Call, a textbox to record the time of the call opens (there's also a textbox to record the date, but it applies to both calls and letters, so it stays visible). Choosing Phone Call also enables/disenables another radio button ("rblSuccess") that records whether the contact attempt was successful. The options for rblSuccess are N/A, No and Yes. The N/A option applies when the user chooses Letter from rblAttemptType, in which case rblSuccess is also disabled (and more fields in the DetailsView become visible).
But if the user chooses Phone Call from rblAttemptType, rblSuccess is selection-cleared and enabled. Choosing no on rblSuccess reveals a drop-down list containing explanatory options (no answer, left voicemail etc.). One of the options is Other, which is supposed to reveal a textbox to record details.
Everything works, right up until that last step. It goes like this: I choose Phone Call, and the Time textbox appears. I type in the date and the time, then select No on rblSuccess, and the drop-down list appears. But when I make a selection on the drop-down list, nothing happens; i.e. the SelectedIndexChanged event assigned to the control isn't firing. And yes, it's set to AutoPostBack="True."
So--again--the SelectedIndexChanged subs for both of the radio buttons are working fine, but the one for the drop-down list isn't being hit.
Here's the code. I'm only including the parts of the DetailsView pertinent to this issue; let me know if you want the whole thing).
From the aspx page:
<asp:DetailsView ID="dvAppointment" runat="server" AutoGenerateRows="False" DataKeyNames="aID"
Visible="False" Caption="Appointment Details" BorderColor="#189AA1" BorderStyle="Solid"
BorderWidth="1px">
<RowStyle BackColor="White" BorderStyle="None" Font-Names="Verdana,Arial,Helvetica"
Font-Size="11px" Font-Strikeout="False" />
<FieldHeaderStyle BackColor="#449c77" CssClass="white" Font-Bold="True" Width="15%"
BorderColor="#189AA1" BorderStyle="Solid" BorderWidth="1px" />
<Fields>
<asp:BoundField DataField="aID" HeaderText="aID" Visible="False" ReadOnly="True" />
<asp:TemplateField HeaderText="Attempt Type" SortExpression="AttemptType" HeaderStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Label ID="lblAttemptType" runat="server" Text='<%# Eval("AttemptTypeDetails") %>'></asp:Label>
<br />
<asp:Label ID="lblAttemptMessage" runat="server" Text='<%# ContactAttemptMessage()%>'
HtmlEncode="False" CssClass="FireBrick9" HtmlEncodeFormatString="False" />
</ItemTemplate>
<InsertItemTemplate>
<asp:Label ID="lblAttemptMessage" runat="server" Text='<%# ContactAttemptMessage()%>'
HtmlEncode="False" CssClass="FireBrick9" HtmlEncodeFormatString="False" />
<asp:RadioButtonList ID="rblAttemptType" runat="server" RepeatDirection="Horizontal"
AutoPostBack="true" OnSelectedIndexChanged="rblAttemptTypeChanged" CssClass="Text9B">
<asp:ListItem Value="1">Phone call</asp:ListItem>
<asp:ListItem Value="2">Letter</asp:ListItem>
</asp:RadioButtonList>
</InsertItemTemplate>
<HeaderStyle VerticalAlign="Middle"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attempt Date" SortExpression="AttemptDate">
<ItemTemplate>
<asp:Label ID="lblAttemptDateWithTime" runat="server" Text='<%# AttemptDateDetails() %>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txAttemptDate" runat="server" AutoCompleteType="Disabled" AutoPostBack="False"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderAttemptDate" runat="server" TodaysDateFormat="mm/dd/yyyy"
TargetControlID="txAttemptDate">
</asp:CalendarExtender>
<asp:UpdatePanel ID="UpdatePanelforAttempt" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="AttemptTimeLabel" runat="server" Text="Time of phone attempt (hh:mm AM/PM): "
Visible="False"></asp:Label>
<asp:TextBox ID="txAttemptTime" runat="server" ToolTip="Time should be in format XX:XX AM/PM"
Visible="False"></asp:TextBox>
<asp:MaskedEditExtender ID="txAttemptTimeTime_MaskedEditExtender" runat="server"
CultureAMPMPlaceholder="" CultureCurrencySymbolPlaceholder="" CultureDateFormat=""
CultureDatePlaceholder="" CultureDecimalPlaceholder="" CultureThousandsPlaceholder=""
CultureTimePlaceholder="" Enabled="True" TargetControlID="txAttemptTime" Mask="99:99 LL"
ClearMaskOnLostFocus="False" MaskType="Number">
</asp:MaskedEditExtender>
<asp:Label ID="LabelSuccess" runat="server" Text="<br /><br />Was the attempt successful?"
CssClass="Text8B" ></asp:Label>
<asp:RadioButtonList ID="rblSuccess" runat="server" OnSelectedIndexChanged="rblSuccessChanged"
RepeatDirection="Horizontal" AutoPostBack="True"
Enabled='<%# IIF(Eval("AttemptType")=1,"true","false") %>'>
<asp:ListItem Value="2">Yes</asp:ListItem>
<asp:ListItem Value="1">No</asp:ListItem>
<asp:ListItem Value="0" Selected="True">N/A</asp:ListItem>
</asp:RadioButtonList>
<asp:Label ID="lblNoContactReason" runat="server" Text="<br />Please clarify the contact attempt result:"
Visible="False" CssClass="smTextItalic"></asp:Label>
<asp:DropDownList ID="ddlrncType" runat="server" DataSourceID="sdsrncTypes" DataValueField="rncTypeID"
DataTextField="rncType" Visible="false" AutoPostBack="True" OnSelectedIndexChanged="ddlrncTypeChanged">
</asp:DropDownList>
<asp:Label ID="lblSpecify" runat="server" Text="<br /><br />Please Explain:<br />"
CssClass="smTextbold" Visible="False"></asp:Label>
<asp:TextBox ID="txrncOther" runat="server" Visible="false" ToolTip="Specific result (350 characters allowed)"
TextMode="MultiLine" CssClass="MultiLineInsert" Width="35%" />
</ContentTemplate>
</asp:UpdatePanel>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
<HeaderStyle BackColor="#449C77" BorderColor="#189AA1" BorderStyle="Solid" BorderWidth="1px" />
<InsertRowStyle Width="80%" BackColor="White" Font-Names="Verdana,Ariel,Helvetica"
Font-Size="11px" />
<EditRowStyle Width="77%" BackColor="White" Font-Names="Verdana,Ariel,Helvetica"
Font-Size="11px" />
<AlternatingRowStyle BackColor="#CFCFCF" Font-Names="Verdana,Ariel,Helvetica" Font-Size="11px" />
</asp:DetailsView>
From the VB code:
Protected Sub rblAttemptTypeChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim iAttemptTimeLabel As Label = DirectCast(dvAppointment.FindControl("AttemptTimeLabel"), Label)
Dim itxAttemptTime As TextBox = DirectCast(dvAppointment.FindControl("txAttemptTime"), TextBox)
Dim irblSuccess As RadioButtonList = DirectCast(dvAppointment.FindControl("rblSuccess"), RadioButtonList)
Dim iUpdatePanelforAttempt As UpdatePanel = DirectCast(dvAppointment.FindControl("UpdatePanelforAttempt"), UpdatePanel)
Dim AttemptType As Integer = 0
If Not sender.selectedValue = String.Empty Then
AttemptType = CInt(sender.selectedValue)
ViewState("AttemptType") = CInt(sender.selectedValue)
If AttemptType = 1 Then 'Phone
If Not iAttemptTimeLabel Is Nothing Then
iAttemptTimeLabel.Visible = True
End If
If Not itxAttemptTime Is Nothing Then
itxAttemptTime.Visible = True
End If
If Not irblSuccess Is Nothing Then
irblSuccess.Enabled = True
irblSuccess.ClearSelection()
End If
ElseIf AttemptType = 2 Then 'Letter
If Not iAttemptTimeLabel Is Nothing Then
iAttemptTimeLabel.Visible = False
End If
If Not itxAttemptTime Is Nothing Then
itxAttemptTime.Visible = False
End If
If Not irblSuccess Is Nothing Then
irblSuccess.Enabled = False
irblSuccess.SelectedIndex = 2
End If
End If
If Not iUpdatePanelforAttempt Is Nothing Then
iUpdatePanelforAttempt.Update()
End If
End If
End Sub
Protected Sub rblSuccessChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim iddlrncType As DropDownList = DirectCast(dvAppointment.FindControl("ddlrncType"), DropDownList)
Dim itxrncOther As TextBox = DirectCast(dvAppointment.FindControl("txrncOther"), TextBox)
Dim ilblNoContactReason As Label = DirectCast(dvAppointment.FindControl("lblNoContactReason"), Label)
Dim iUpdatePanelforAttempt As UpdatePanel = DirectCast(dvAppointment.FindControl("UpdatePanelforAttempt"), UpdatePanel)
Dim Success as Integer = -1
If Not sender.selectedValue = String.Empty Then
Success = CInt(sender.selectedValue)
If Success = 1 Then
If Not iddlrncType Is Nothing Then
iddlrncType.Visible = True
End If
If Not ilblNoContactReason Is Nothing Then
ilblNoContactReason.Visible = True
End If
Else
If Not iddlrncType Is Nothing Then
iddlrncType.Visible = False
End If
If Not ilblNoContactReason Is Nothing Then
ilblNoContactReason.Visible = False
End If
End If
If Not iUpdatePanelforAttempt Is Nothing Then
iUpdatePanelforAttempt.Update()
End If
End If
End Sub
Protected Sub ddlrncTypeChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ilblSpecify As Label = CType(dvAppointment.FindControl("lblSpecify"), Label)
Dim itxrncOther As TextBox = CType(dvAppointment.FindControl("txrncOther"), TextBox)
Dim iUpdatePanelforAttempt As UpdatePanel = DirectCast(dvAppointment.FindControl("UpdatePanelforAttempt"), UpdatePanel)
Dim rncTypeID as Integer = 0
If Not sender.selectedValue = String.Empty AndAlso IsNumeric(sender.selectedvalue) Then
rncTypeID = CInt(sender.selectedValue)
If rncTypeID = 5 Then
If Not itxrncOther Is Nothing Then
itxrncOther.Visible = True
itxrncOther.Focus()
If Not ilblSpecify Is Nothing Then
ilblSpecify.Visible = True
End If
End If
Else
If Not itxrncOther Is Nothing Then
itxrncOther.Visible = False
If Not ilblSpecify Is Nothing Then
ilblSpecify.Visible = False
End If
End If
End If
If Not iUpdatePanelforAttempt Is Nothing Then
iUpdatePanelforAttempt.Update()
End If
End If
End Sub
I tried adding a second Update Panel, just around the drop-down list and the "Other" textbox, with the drop-down assigned as the AsyncPostBackTrigger, but it didn't make a difference.
Related
I have following gridview in aspx page:
<asp:GridView Runat="server" id="gv1" PageSize="20" Visible="False" AllowPaging="True" Width="100%"
CssClass="clsDataGrid" AutoGenerateColumns="false" DataKeyNames="intProofSLNo,txtAdminRemarks" CommandArgument='Eval(intProofSLNo,txtAdminRemarks)'
OnRowCommand="gv1_RowCommand" OnRowDataBound ="gv1_OnRowDataBound" >
<asp:BoundField DataField="intProofSLNo" ReadOnly="True" Visible="false" ItemStyle-Wrap="false" HeaderText="Sl No" ItemStyle-CssClass="clsNormalText"></asp:BoundField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnApprove" runat="server" CommandName="Approve" Text= "Approve / " />
<asp:LinkButton ID="lnkbtnReject" runat="server" CommandName="Reject" Text= "Reject" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Admin Remarks">
<ItemTemplate>
<asp:Label ID="lblAdminRemarks" runat="server" ItemStyle-Wrap="True" Text='<%# Bind("txtAdminRemarks")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAdminRemarksEdit" runat="server" cssclass=clsCommonInput MaxLength="252" Text='<%# DataBinder.Eval(Container.DataItem, "txtAdminRemarks")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lblEdit" runat="server" Text="Edit" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" Width="38" runat="server" Text="Update|" CommandName="Update"CommandArgument='<%# Container.DataItemIndex %>' CausesValidation="true" ToolTip="Save"> </asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" Width="40" Text="Cancel" CommandName="Cancel"
CausesValidation="false" ToolTip="Reset"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The user clicks on the 'Edit' link which makes 'Update' and 'Cancel' links visible.It then enters the remarks in the textbox and clicks 'Update'.A row command event is fired which updates the remarks in DB for the entry in that particular row. The same event calls the bind function:
Protected Sub gv1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Update" Then
//some code to update remarks//
gv1.EditIndex = -1
subBindDataGrid()
End If
The subBindDataGrid() fires the following rowbound event which hides the buttons depending on admin remarks:
Protected Sub gv1_OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblAdminRemarks As Label = DirectCast(e.Row.FindControl("lblAdminRemarks"), Label)
Dim lnkReject As LinkButton = DirectCast(e.Row.FindControl("lnkbtnReject"), LinkButton)
Dim lnkApprove As LinkButton = DirectCast(e.Row.FindControl("lnkbtnApprove"), LinkButton)
Dim lnkEdit As LinkButton = DirectCast(e.Row.FindControl("lblEdit"), LinkButton)
If DataBinder.Eval(e.Row.DataItem, "txtAdminRemarks").ToString().Trim = "Auto-Approved" Then
lnkApprove.Visible = False
lnkReject.Visible = False
lnkEdit.Visible = False
Else
lnkbtnApprove.Visible = True
lnkbtnReject.Visible = True
End If
End If
The remarks get updated in the DB. However, there is some issue in binding and instead of displaying the grid, the page is redirected to an error page. There is no exception thrown anywhere while debugging. The same events are also called in 'Edit'command. However, the functionality works fine there.Please suggest if there is anything wrong with the syntax.
I see you don't define a DataSourceID on the GridView static definition, please make sure you define a DataSource for the GridView in the subBindDataGrid procedure, otherwise it will have a null datasource in input.
I am getting the output of 0 and I don't know what I am doing wrong. I using the findcontrol method to find the IDs within the Gridview and declaring them as radiobuttons, then I am trying to use an if statement to assign the checked radio button a value, then output that value to a label.
vb code
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim numOutput As Integer
For Each row As GridViewRow In GridView1.Rows
Dim qID As Label = row.FindControl("QuestionID")
Dim rd1 As RadioButton = TryCast(row.FindControl("answer1"), RadioButton)
Dim rd2 As RadioButton = TryCast(row.FindControl("answer2"), RadioButton)
Dim rd3 As RadioButton = TryCast(row.FindControl("answer3"), RadioButton)
Dim rd4 As RadioButton = TryCast(row.FindControl("answer4"), RadioButton)
If rd1.Checked = True Then
numOutput = 1
ElseIf rd2.Checked = True Then
numOutput = 2
ElseIf rd3.Checked = True Then
numOutput = 3
ElseIf rd4.Checked = True Then
numOutput = 4
End If
Next
lblOutput.Text = numOutput
End Sub
Source code
<asp:GridView ShowHeader="false" AutoGenerateColumns="false" ID="GridView1" runat="server" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="QuestionID" Text='<%# Eval("QuestionID")%>' />
<asp:Label runat="server" ID="Question" Text='<%# Eval("Question")%>' /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer1")%>' runat="server" ID="answer1" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer2")%>' runat="server" ID="answer2" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer3")%>' runat="server" ID="answer3" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer4")%>' runat="server" ID="answer4" /><hr />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:Label ID="lblOutput" runat="server" Text="" />
Your bug
I don't know what's wrong with your code because I can't debug your code for see what happens on your VB code. If you don't know how you can debug your code, please watch this YouTube video about debugging.
My suggestion
I suggest you to place all your check boxes onto a panel and loop over all the items of that control. I go check if each control is a RadioButton. if yes, cast that onto a RadioButton and check if the RadioButton is checked. If yes, counter can be display in your label.
The counter counts witch RadioButton is checked and is also the output you can show on your label. See also code for more information for what I do.
Don't forget to add one to the counter or it will stay on the same value.
Here is the VB code:
Dim counter As Integer = 0
For Each contr As Control In pnlAnswers.Controls 'loop over each control on the panel
If TypeOf contr Is RadioButton Then 'Check if contr is a RadioButton
RadioButton rdb = CType(contr, RadioButton) 'if yes cast it to a RadioButton
If rdb.Checked Then 'If checked
lblOutput.Text = counter.ToString() 'Place the tag value on the output label
Return
End If
counter += 1
End If
Next
Place also your labels outside the panel. Note that it has no impact for the code behind if the labels are inside the panel. The loop will skip them because a label is not a type of a radio button. But it beter that the labels are outside when you add some features to your application.
Here is the ASP code:
<asp:Label runat="server" ID="QuestionID" Text='<%# Eval("QuestionID")%>' />
<asp:Label runat="server" ID="Question" Text='<%# Eval("Question")%>' /><br />
<asp:panel ID="pnlAnswers" runat="server">
<asp:RadioButton GroupName="a" Text='<%# Eval("answer1")%>' runat="server" ID="answer1" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer2")%>' runat="server" ID="answer2" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer3")%>' runat="server" ID="answer3" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer4")%>' runat="server" ID="answer4" />
</asp:panel>
P.S.: The tags I've added on a previous update aren't necessary now.
Code clean up
I've also removed this line of code:
Dim qID As Label = row.FindControl("QuestionID")
I can't find any line where you use this line so it's overkill to find your label QuestionID.
Notes
It's a long time ago I've used VB.NET and ASP.NET web forms so please comment me if the code is not working.
#SOreadytohelp
I am trying to find a radiobutton control within a gridview but I keep getting the output of 0 for whatever radiobutton I select. I want each radiobutton to be assigned the value of 1-4 and then whatever radiobutton selected, it will be outputted to a label.
VB code
Dim SelectNumber As Integer
For Each row As GridViewRow In MyGridView.Rows
Dim radbtn1 As RadioButton = TryCast(row.FindControl("a1"), RadioButton)
Dim radbtn2 As RadioButton = TryCast(row.FindControl("a2"), RadioButton)
Dim radbtn3 As RadioButton = TryCast(row.FindControl("a3"), RadioButton)
Dim radbtn4 As RadioButton = TryCast(row.FindControl("a4"), RadioButton)
If radbtn1.Checked = True Then
SelectNumber = 1
ElseIf radbtn2.Checked = True Then
SelectNumber = 2
ElseIf radbtn3.Checked = True Then
SelectNumber = 3
ElseIf radbtn4.Checked = True Then
SelectNumber = 4
End If
Next
lblOutput.Text = SelectNumber
Source code
<asp:GridView ShowHeader="false" AutoGenerateColumns="false" ID="MyGridView" runat="server" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="QuestionID" Text='<%# Eval("QuestionID")%>' />
<asp:Label runat="server" ID="Question" Text='<%# Eval("Question")%>' /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a1")%>' runat="server" ID="ans1" /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a2")%>' runat="server" ID="ans2" /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a3")%>' runat="server" ID="ans3" /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a4")%>' runat="server" ID="ans4" /><hr />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Complete" />
<asp:Label ID="lblOutput" runat="server" Text="" />
I'm pretty sure that the reason for this issue is that you databind the grid on every postback instead of only If Not Page.IsPostback. Then no one is checked and the SelectNumber keeps it's default value which is 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
' DataBind the GridView here or call a method therefore '
End If
End Sub
Within my ASP gridview, I have the following (updated to show full gridview):
<asp:GridView ID="TPAnnuity_GridView" AllowSorting="true" AllowPaging="true" Runat="server"
DataSourceID="TPAnnuity_SqlDataSource" DataKeyNames="AnnuityTotalPointsID"
AutoGenerateColumns="False" ShowFooter="true" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Company" SortExpression="CompanyName" HeaderStyle-VerticalAlign="Bottom">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EditACompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName" selectedValue='<%# Bind("CompanyID") %>'></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewCompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="NewCompanyID" Display="Dynamic" ForeColor="" ErrorMessage="You must enter a value. *" Enabled="false"></asp:RequiredFieldValidator>
</FooterTemplate>
<FooterStyle Wrap="False" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<br />
<i>No Commission Data to display.</i>
<br />
<br />
</EmptyDataTemplate>
</asp:GridView>
And within my back end, I have the following:
Sub TPAnnuity_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles TPAnnuity_GridView.RowCommand
If e.CommandName = "Cancel" Then
'Reset Footer Row input fields
CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedIndex = 0
ElseIf e.CommandName = "Insert" Then
TPAnnuity_SqlDataSource.InsertParameters.Clear()
Dim test1 As New Parameter("CompanyIDInt", TypeCode.Int32)
test1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedValue
TPAnnuity_SqlDataSource.InsertParameters.Add(test1)
TPAnnuity_SqlDataSource.Insert()
ElseIf e.CommandName = "Update" Then
TPAnnuity_SqlDataSource.UpdateParameters.Clear()
Dim param1 As New Parameter("CompanyIDInt", TypeCode.Int32)
param1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("EditACompanyID"), DropDownList).SelectedValue ****THIS IS THE PROBLEM LINE****
TPAnnuity_SqlDataSource.UpdateParameters.Add(param1)
TPAnnuity_SqlDataSource.Update()
End If
End Sub
The Cancel and Insert functions work just fine, operating off of the footer. Every time hit the "Update" button, I get a NullReferenceException on the param1.Default Value = line.
Can anyone help me figure out what's going on here?
Your row should look like this:
param1.DefaultValue = CType(e.CommandSource.FindControl("EditACompanyID"), DropDownList).SelectedValue
Instead of utilizing the FooterRow, you have to use the source row. Since you passed that in with e, you can use this.
I've written some code in the Page_PreRender event that gets the value of a DropDownList control and then performs some conditional logic. Problem is, the logic must not be very good.
The first If.. Then.. Else.. structure is working fine, however, if the selectedItem is not "Todos" (portuguese for "all") all the rows' visibility will be set to false. The issue seems to arise when the If SelectedItem <> "Todos" Then condition is met.
So, every option in the DropDownList aside from "Todos" sets the visibility of all rows to False instead of setting the visibility of the ones that don't match the SelectedItem to False.
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
'Getting the selected item
Dim SelectedItem As String = CType(GridView1.HeaderRow.Cells(3).FindControl("DropDownList1"), DropDownList).SelectedItem.Text
If SelectedItem <> "Todos" Then
'This is the part where the issue seems to be located.
For Each Row As GridViewRow In GridView1.Rows
'Get the Text value
Dim depar As String = Row.Cells(3).Text
'If its different from the SelectedItem then the row's visible property should be set to false, if it's a match, set it to true.
If depar <> SelectedItem Then
Row.Visible = False
ElseIf depar = SelectedItem Then
Row.Visible = True
End If
Next
'If "Todos" was selected, all rows should be visible
ElseIf SelectedItem = "Todos" Then
'Make all rows visible
For Each row As GridViewRow In GridView1.Rows
row.Visible = True
Next
End If
End Sub
Code of GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" PageSize="20" Width="100%" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#CType(Container, GridViewRow).DataItem("IdPedido") %>' OnClick="LinkButton1_Click" OnCommand="LinkButton1_Command">Ver</asp:LinkButton>
</ItemTemplate>
<HeaderStyle Width="40px" />
</asp:TemplateField>
<asp:BoundField DataField="Observacoes" HeaderText="Assunto" SortExpression="Observacoes" />
<asp:BoundField DataField="NomeHotel" HeaderText="Hotel" SortExpression="NomeHotel" />
<asp:TemplateField HeaderText="Departamento" SortExpression="NomeDepartamento">
<HeaderTemplate>
Departamento<br />
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" DataSourceID="SqlDataSource1" DataTextField="NomeDepartamento" DataValueField="IdDepartamento" AutoPostBack="True" OnLoad="DropDownList1_Load" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Todos</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EnotelSuporteConnectionString1 %>" SelectCommand="SELECT [NomeDepartamento], [IdDepartamento] FROM [Departamentos]"></asp:SqlDataSource>
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NomeDepartamento") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("NomeDepartamento") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DataPedido" HeaderText="Data" DataFormatString = "{0:dd, MMM yyyy}" SortExpression="DataPedido" />
<asp:BoundField DataField="DataFinalizado" HeaderText="Finalizado a" DataFormatString = "{0:dd, MMM yyyy}" SortExpression="DataFinalizado" />
<asp:BoundField DataField="Nome" HeaderText="Nome" SortExpression="Nome" />
<asp:BoundField DataField="Estado" HeaderText="Estado" SortExpression="Estado" Visible="False" />
<asp:BoundField DataField="IdPedido" HeaderText="IdPedido" InsertVisible="False" ReadOnly="True" SortExpression="IdPedido" Visible="False" />
</Columns>
</asp:GridView>
THe problem in your Row.Cells(3).Text is that you are defining the ItemTemplate in your gridview with Label and to get the ItemTemplates value you have to first find the control and then get the value from that control.
If you want the value of the label then use the following code to get the value,
Label label = (Label)Row.Cells(3).FindControl("Label1");
if(label != null)
string depar = label.Text;
NOTE
Code is in the c# you might want to convert it to the VB.