I have a ListView that populates and displays a user's data (via a profile system in VWD 2008) during Page_Load and also when I go from the EditItemTemplate to the ItemTemplate.
When I go to the edit screen again, my DropDownList and RadioButtonList controls display the first items in the corresponding tables instead of the correct profile values.
I don't understand why the controls populate correctly the first and second times but not on the third time (that's right, the third time is NOT a charm).
Can someone can help me understand how to solve this problem?
ItemTemplate:
<asp:DropDownList ID="ddlTState" AppendDataBoundItems="True"
DataSourceID="srcState" DataTextField="StateName" DataValueField="StateName"
Enabled="False" TabIndex="125" runat="server" />
EditItemTemplate:
<asp:DropDownList ID="ddlEState" AppendDataBoundItems="true"
DataSourceID="srcState" DataTextField="StateName"
DataValueField="StateName" TabIndex="125" runat="server">
<asp:ListItem Text="--State--" Value="" />
VB code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
lsv = Util.FindChild(Me, "lsvProfile")
'If Not IsPostBack Then
ddl = Util.FindChild(lsv, "ddlEState") 'Util.FindChild = my version of FindControl
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
ddl = Util.FindChild(lsv, "ddlTState")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
'End If
End Sub
It could be it's hitting the null condition and not writing; a better way to handle items/edit template is to tap into the ItemDataBound event or ItemCreated event handlers. This features at the time it creates the row, and you will have better success there. I believe you could also leverage ItemEditing, which fires when a row switches to edit mode, as another way to process an edit action.
EDIT: Try to do this:
protected void lsvProfile_ItemDataBound(..)
{
if (e.Item.ItemTYpe == ListViewItemType.DataItem)
{
DropDownList d = e.Item.FindControl("ddlTState") as DropDownList;
}
}
And debug to see if that is null or not null. The only time that should be null is if its rendering the header/footer or the edit item... That should work though, I do that all the time.
HTH.
Thanks, Brian. I resolved it with this code before I read your latest post:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
lsv = Util.FindChild(Page, "lsvProfile")
If Not IsPostBack Then
Try
lsv.EditIndex = 0
rbl = Util.FindChild(lsv, "rblEGender")
If rbl IsNot Nothing Then rbl.SelectedValue = Profile.Gender
ddl = Util.FindChild(lsv, "ddlEState")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
ddl = Util.FindChild(lsv, "ddlEBirthDay")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthDay
ddl = Util.FindChild(lsv, "ddlEBirthMo")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthMo
Catch ex As Exception
End Try
End If
End Sub
Protected Sub lsvProfile_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lsvProfile.ItemDataBound
ddl = Util.FindChild(Me, "ddlEState")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
ddl = Util.FindChild(Me, "ddlEBirthMo")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthMo
ddl = Util.FindChild(Me, "ddlEBirthDay")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthDay
rbl = Util.FindChild(Me, "rblEGender")
If rbl IsNot Nothing Then rbl.SelectedValue = Profile.Gender
End Sub
Related
I have 3 textboxes that have AutoPostBack = true. On postback it's losing it's focus. I've been searching and tried many things but nothing is working.
The code below is a snippet of what i'm trying to do.
basically this first snippet isn't grabbing anything. Does anyone know what i'm doing wrong here
**Side note I'm not using Update Panel i'm using LayoutItemNestedControlContainer
Dim ctrl = From control In wcICausedPostBack.Parent.Controls.OfType(Of WebControl)()
Where control.TabIndex > indx
Select control
Protected Sub txtDEPTH_TextChanged(sender As Object, e As EventArgs) Handles txtDEPTH.TextChanged
UpdateProductTemp()
txtDEPTH.Focus()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim wcICausedPostBack As WebControl = CType(GetControlThatCausedPostBack(TryCast(sender, Page)), WebControl)
Dim indx As Integer = wcICausedPostBack.TabIndex
Dim ctrl = From control In wcICausedPostBack.Parent.Controls.OfType(Of WebControl)()
Where control.TabIndex > indx
Select control
ctrl.DefaultIfEmpty(wcICausedPostBack).First().Focus()
End If
End Sub
Protected Function GetControlThatCausedPostBack(ByVal page As Page) As Control
Dim control As WebControl = Nothing
Dim ctrlname As String = page.Request.Params.[Get]("__EVENTTARGET")
If ctrlname IsNot Nothing AndAlso ctrlname <> String.Empty Then
control = page.FindControl(ctrlname)
Else
For Each ctl As String In page.Request.Form
Dim c As Control = page.FindControl(ctl)
If TypeOf c Is TextBox OrElse TypeOf c Is DropDownList Then
control = c
Exit For
End If
Next
End If
Return control
End Function
Which version are you using? Because, when I try to set focus() of a Textbox, the compiler gives me an error, because there is no such method. However, HTML provides an attribute, which auto focuses an focusable element.
Solution:
TextBoxToSetFocus.Attributes.Add("autofocus", "")
Regards,
Maheshvara
I have a DetailsView which contains several text boxes and also a DropDownList.
Now, what I want to do is to write an SelectedIndexChanged event for that DropDownList, but my problem is that I cannot reach it anymore/reference it.
If I just put a DropDownList right on the form it´s no problem but now winds it is inside the DetailsView it seems impossible to reach it.
Any suggestions?
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Protected Sub DetailsViewAvtaleInfo_PageIndexChanging1(sender As Object, e As DetailsViewPageEventArgs) Handles DetailsViewAvtaleInfo.PageIndexChanging
Dim DropDownListContractType As DropDownList = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("DropDownListContractType"), DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.Text = "Kjøp" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
I know this is not right, but its as far as I get. I would want to just Write the code within the following sub but it just will not work:
Protected Sub DropDownListContractType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListContractType.SelectedIndexChanged
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.Text = "Leasing" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
You did not post the markup for the dropdownlist, it should be like below (Attached the method to the event):
<asp:DropDownList ID="DropDownListContractType" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownListContractType_SelectedIndexChanged">
<asp:ListItem Text="Kjøp" Value="2"></asp:ListItem>
<asp:ListItem Text="Leasing" Value="1"></asp:ListItem>
</asp:DropDownList>
Your code also have some issues:
Should be DropDownList.SelectedItem.Text instead of
DropDownList.Text.
You have to cast the sender to DropDownList in DropDownListContractType_SelectedIndexChanged method.
You have to find the NamingContainer of DropDownList in DropDownListContractType_SelectedIndexChanged method
If you have the following code, it should work:
Protected Sub DropDownListContractType_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim DropDownListContractType As DropDownList = DirectCast(sender, DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(DropDownListContractType.NamingContainer.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.SelectedItem.Text = "Leasing" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
Protected Sub DetailsViewAvtaleInfo_PageIndexChanging(sender As Object, e As DetailsViewPageEventArgs) Handles DetailsViewAvtaleInfo.PageIndexChanging
Dim DropDownListContractType As DropDownList = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("DropDownListContractType"), DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.SelectedItem.Text = "Kjøp" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
I have tested the code above. If you have any issue, try to copy/paste the markup and code.
You can download my test project to compare with yours here.
I am trying to set the selected value of a radiobuttonlist that is a template column within a gridview. I am having to do this using the code behind as the database field containing the data (Status) contains null values hence I cant used SelectedValue='<%# Bind("Status") %>' on the asp side.
It has been suggested that I use onRowDataBound to do this and use DataItem to retrieve the value from the datasource and used it to set the radiobuttonlist selected value but I'm not sure how to do this in vb code.
I've tried the following:
Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim radioList = TryCast(e.Row.FindControl("rblActions"), RadioButtonList)
' this will be the object that you are binding to the grid
Dim myObject = TryCast(e.Row.DataItem, DataRowView)
Dim sStatus As String = Convert.ToString(myObject("Status"))
If sStatus <> Nothing Then
radioList.SelectedValue = sStatus
End If
End If
End Sub
but it hasnt work. Any help would be appreciated. Thanks
Found my own solution as follows:
Sub gv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rbl As RadioButtonList = CType(e.Row.FindControl("rblActions"), RadioButtonList)
Dim selected As String = e.Row.DataItem("Status").ToString
If Not IsNothing(selected) Then
rbl.SelectedValue = selected
End If
End If
End Sub
I have a "cart" Repeater, where every item has a couple of controls in it. The ones we're focusing on are two DropDownLists, a LinkButton and a TextBox. The lists are on one validation group and the button & textbox are on another.
Both lists have an OnSelectedIndexChanged event handler which does some calculations based on the selections in both DropDownLists. Both lists also have AutoPostBack="True".
The button has an OnClick handler which also does some calculations according to the number in the textbox.
I need the calculations to be updated immediately - so I added another data binding for the Repeater - on each event handler
The problem is - I can't get the value from the TextBox after I click on one of the DropDownLists. It always comes off as 1. In the background, the OnSelectedIndexChanged event handler fires first, and the buttons' OnClick will fires after it. That only happens after I change one of the lists - and it happens every time I click that button from that moment on. Before that - everything is normal on all controls.
What do you think? Below is some code (I hope it's not too much, I included everything that's taking part) - Thank you very much!
Here's the repeater template:
<ItemTemplate>
<tr>
<td class="size"><div><asp:DropDownList runat="server" ID="_selectSize" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>" ValidationGroup="doNotValidate"></asp:DropDownList></div></td>
<td class="material"><div><asp:DropDownList runat="server" ID="_selectMaterial" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>" ValidationGroup="doNotValidate"></asp:DropDownList></div></td>
<td class="quantity">
<div>
<div class="quantity_container"><asp:TextBox runat="server" ID="_txtAmount" name="quantity_<%#Container.ItemIndex%>" ValidationGroup="vCart"></asp:TextBox></div>
<div><asp:LinkButton runat="server" CssClass="refresh" id="_refreshCart" ValidationGroup="vCart"></asp:LinkButton></div>
</div>
</td>
</tr>
</ItemTemplate>
The Repeater.DataBound():
Protected Sub rptCart_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptCart.ItemDataBound
If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then
Dim OrderItem As ProxyMarket.Item = CType(e.Item.DataItem, ProxyMarket.Item)
Dim btnRemoveProduct As LinkButton = CType(e.Item.FindControl("_removeProduct"), LinkButton)
Dim btnRefreshCart As LinkButton = CType(e.Item.FindControl("_refreshCart"), LinkButton)
Dim txtAmount As TextBox = CType(e.Item.FindControl("_txtAmount"), TextBox)
Dim sizeSelect As DropDownList = CType(e.Item.FindControl("_selectSize"), DropDownList)
Dim materialSelect As DropDownList = CType(e.Item.FindControl("_selectMaterial"), DropDownList)
btnRemoveProduct.CommandName = OrderItem.ID
btnRefreshCart.CommandName = OrderItem.ID
txtAmount.Text = OrderItem.Units
AddHandler btnRemoveProduct.Click, AddressOf removeProduct
AddHandler btnRefreshCart.Click, AddressOf refreshCart
sizeSelect.DataSource = sizeList
sizeSelect.DataBind()
sizeSelect.SelectedIndex = s
materialSelect.DataSource = materialList
materialSelect.DataBind()
materialSelect.SelectedIndex = m
End If
End Sub
Here is the DropDownLists event handler:
Protected Sub selectChange(ByVal sender As DropDownList, ByVal e As System.EventArgs)
Dim listing As New PriceListing
Dim ddl As DropDownList
Dim selectedIndex As Integer
If sender.ID = "_selectSize" Then
For Each rptrItem As RepeaterItem In rptCart.Items
ddl = CType(rptrItem.FindControl("_selectMaterial"), DropDownList)
If ddl.TabIndex = sender.TabIndex Then Exit For
Next
For Each listing In artDecoPricing
If listing.Size = sender.SelectedValue Then Exit For
Next
selectedIndex = ddl.SelectedIndex
s = sender.SelectedIndex
ElseIf sender.ID = "_selectMaterial" Then
For Each rptrItem As RepeaterItem In rptCart.Items
ddl = CType(rptrItem.FindControl("_selectSize"), DropDownList)
If ddl.TabIndex = sender.TabIndex Then Exit For
Next
For Each listing In artDecoPricing
If listing.Size = ddl.SelectedValue Then Exit For
Next
selectedIndex = sender.SelectedIndex
s = ddl.SelectedIndex
End If
Select Case selectedIndex
Case 0
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Canvas
Case 1
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Acrylic
Case 2
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Framed
Case 3
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Alucobond
End Select
Cart.SaveOrder()
s = sender.SelectedIndex
m = selectedIndex
rptCart.DataSource = Cart.Order.Items
rptCart.DataBind()
End Sub
And finally, the LinkButton OnClick handler:
Protected Sub refreshCart(ByVal sender As Object, ByVal e As System.EventArgs)
Dim btnRefreshCart As LinkButton = CType(sender, LinkButton)
Dim amountStr As String
Dim amount As Integer
amountStr = CType(btnRefreshCart.Parent.FindControl("_txtAmount"), TextBox).Text
If IsNumeric(amountStr) Then
amount = CDbl(amountStr)
Else
amount = -1
End If
amount = IIf(amount > 0, amount, -30)
For Each Item As ProxyMarket.Item In Cart.Order.Items
If Item.ID = btnRefreshCart.CommandName Then
Item.Units = amount
Cart.Edit_Product(btnRefreshCart.CommandName, amount)
Exit For
End If
Next
rptCart.DataSource = Cart.Order.Items
rptCart.DataBind()
End Sub
Thank you :)
I found a solution!
Apparently this is happening because of a viewstate limitation in ASP.NET which causes the OnSelectedIndexChanged to fire on Page_Load regardless if the user actually selected a different value.
So when the event handler fires, I am checking whether it is the DropDownLists which called me or a different control - that prevents the event from firing when it doesn't need to - and keeps all event handling on the page intact:
Protected Sub selectChange(ByVal sender As DropDownList, ByVal e As System.EventArgs)
Dim senderClientID = Page.Request.Params.Get("__EVENTTARGET")
' Run ONLY if the relevant select control was clicked,
' otherwise this is only fired because of ASP.NET limitations,
' and will screw up the original event:
If senderClientID.IndexOf("_selectSize") <> -1 Or senderClientID.IndexOf("_selectMaterial") <> -1 Then
'do stuff
I know this has already been answered but I was having a very similar problem, with a completely different solution and as this is the first post that appeared in google I thought I would add it here.
I had a link button and when clicking it, but only in IE9, it appeared to activate another button on the page and call it's event rather than it's own.
After much messing about and googling, I realised that it wasn't just my button that was activating the other button it was if I clicked anywhere in a particular section of my page.
I eventually found the problem after completely stripping down my page. It was this:
<label style="width: 100%" />
an empty label tag. Once deleted all was fine.
I am using following code in rowdatabound function.
Protected Sub gvwMileStone_RowDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Footer Then
Dim ddlItem As DropDownList = CType(e.Row.FindControl("ddlFProjectLevels"), DropDownList)
If ddlItem IsNot Nothing Then
ddlItem.DataSource = objMileStone.GetProjectLevels()
ddlItem.DataValueField = "MileStoneID"
ddlItem.DataTextField = "Name"
ddlItem.DataBind()
End If
End If
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowState = DataControlRowState.Edit Then
Dim ddlEProjectLevels As DropDownList = CType(e.Row.FindControl("ddlEProjectLevels"), DropDownList)
ddlEProjectLevels.DataSource = objMileStone.GetProjectLevels()
ddlEProjectLevels.DataValueField = "MileStoneID"
ddlEProjectLevels.DataTextField = "Name"
ddlEProjectLevels.DataBind()
ddlEProjectLevels.SelectedValue = milestoneid
End If
End If
End Sub
ddlEProjectLevels is dropdownlist in edititemtemplate. When I click edit in 1st row ddlEProjectLevels gets loaded with data from database. But in 2nd row dropdownlist does not contain values. Again in 3rd it gets loaded from db. Means in alternate rows, when I click edit dropdownlist(ddlEProjectLevels) doesn't load values. Can anybody help?
This issue is somewhat confusing compared to other controls and applies to GridView and DetailsView controls. You'll need to check the RowState enumeration using bitwise logic since an item may have a state of Alternate or Edit.
So instead of:
If e.Row.RowState = DataControlRowState.Edit Then
Try:
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
For more info check out the DataControlRowState Enumeration page.