I have a DropDownList() that is rendered in my codebehind and populated by myView
Dim ddl As New DropDownList()
ddl.ID = "ddlV_" & dtrw("col_id") & "_" & fixDisplayName(dtrw("display_name"))
ddl.DataSource = myView
ddl.DataTextField = "DDLTEXT"
ddl.DataValueField = "DDLVALUE"
ddl.AutoPostBack="true"
ddl.DataBind()
I would like to add OnSelectedIndexChanged ="do_this_when_changed" attribute to the above dropdown list.
I do understand that Web server controls are also created on the server and they require a runat="server" attribute to work.
Can this be done for this list control?
You can add an event handler programmatically with AddHandler:
Dim ddl As New DropDownList()
' ... '
AddHandler ddl.SelectedIndexChanged, AddressOf do_this_when_changed
In this class:
Private Sub do_this_when_changed(sender As Object, e As EventArgs)
Dim ddl = DirectCast(sender, DropDownList) ' here it is'
End Sub
You can do it using this event...
ddl.SelectedIndexChanged
Related
I'm creating dynamic LinkButton where I assign to it dynamically an ID now I would be able to write an onClick function where I get that ID but after trying to make something like that I had no result:
table.Append("<td><asp:LinkButton runat=""server"" class=""edit btn btn-sm btn-default"" ID=" & reader.GetString("id") & " OnClient=""Delete_User""><i class=""fa fa-trash-o"" aria-hidden=""true""></asp:LinkButton></i></a>")
While here is VB.NET code
Sub Delete_User(sender As Object, e As EventArgs)
Dim clickedBtn As LinkButton = CType(sender, LinkButton)
MsgBox(clickedBtn.ID)
End Sub
The LinkButton is a server control and you cannot render it with same way as you render plain HTML tags from code-behind, it will not work as expected. You need to provide HtmlTableCell instance and bind LinkButton control from there, assumed table is defined as HtmlTable:
' this is just a sample event
Protected Sub SomeEventHandler(sender As Object, e As EventArgs)
Dim table As HtmlTable = New HtmlTable()
Dim row As HtmlTableRow = New HtmlTableRow()
' set the data reader from database here
Dim cell As HtmlTableCell = New HtmlTableCell()
Dim linkbtn As LinkButton = New LinkButton()
linkbtn.ID = reader.GetString("id") ' setting control ID
linkbtn.Text = "Delete User" ' setting link text
linkbtn.CssClass = "edit btn btn-sm btn-default"
AddHandler lnkbutton.Click, AddressOf Delete_User ' assign event handler
' add the control to table cell ('td' element)
cell.Controls.Add(linkbtn)
row.Cells.Add(cell)
table.Rows.Add(row)
' other stuff
End Sub
Note that you should provide server-side click event with Click property which associated with OnClick event, not OnClient nor OnClientClick.
Additional note:
MsgBox cannot be used in ASP.NET because it belongs to WinForms, you need to provide JS alert() function to show message box with RegisterStartupScript or RegisterClientScriptBlock:
Sub Delete_User(sender As Object, e As EventArgs)
Dim clickedBtn As LinkButton = CType(sender, LinkButton)
Dim message As String = "alert('" & clickedBtn.ID & "');"
Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "MsgBox", message, True)
End Sub
Related issues:
How to add linkbutton control to table cell dynamically
Creating a link button programmatically
How to add dynamically created buttons to a dynamically created table?
I have bind my dropdownlist with database. But on each PostBack the items in dropdownlist gets repeat again.
e.g.
OnPage Load I have this items in dropdownlist 1,2,3,4.. etc Now suppose page gets postBack then it looks like 1,2,3,4,1,2,3,4
Vb code
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateAreas()
End Sub
Private Sub PopulateAreas()
If IsPostBack Then
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity Like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
UPDATE
I have master page which has dropdownlist of cities. I am using masterpage control to mycontent page like below.
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Now in my PopulateArea() class there is query in which WHERE clause have cityselector. So according to city my area gets fetched.
Call your function inside not postback event so that the dropdown is not called on postback events(which fills it everything).
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
if ispostback = false then
Me.PopulateAreas()
end if
End Sub
its pretty simple.. the page load event is triggered every time anything is post back.
use this
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
//do stuff when post back occurs
Else
Me.PopulateAreas() //put this function here so that it executes only once
End If
End Sub
If your dropdown values have to change on the postback. Say initially the values where 1,2,3,4 and on postback if the values has to be 2,3,4,5 based on some of the values you change on the form controls you will have to clear the dropdown values first and then add new values to it.
areasList.Items.Clear()
Also see that AppendDataBoundItems is not true: in your .aspx page
Change your code to,
Private Sub PopulateAreas()
If IsPostBack Then
areasList.Items.clear()
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity Like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
End Sub
This one is REALLY driving me nuts. I've read, and tried, most of the workarounds but still it posts back!!
All the markup is generated dynamically from code-behind and inserted into a page that is part of a Master Page, from the init event.
There are a series of nested tabs, the tab content for the most part is data in a GridView. Each Gridview is set in it's own update panel. Every time a LinkButton in the GridView is clicked there is a full postback causing the tabs to reset (any button outside of the GridView and in the UpdatePanel doesn't cause a full postback.
LinkButtons are generated like this
Dim Select_Field As New CommandField
With Select_Field
.HeaderText = "View Transactions"
.SelectText = "View Transactions"
.ShowSelectButton = True
End With
GV.Columns.Add(Select_Field)
Registering with ToolKitScriptManager
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
AjaxControlToolkit.ToolkitScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(LB)
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
and the generated markup for one row is like this
<tr class="GridView" style="color:#333333;background-color:#F7F6F3;">
<td>10</td>
<td>Adam White</td>
<td>4224 Res Road</td>
<td align="right">$6,850.65</td>
<td>
<a id="ctl00_ContentPlaceHolder1_AssessmentsMainGV_ctl02_AssMain_10" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" style="color:#333333;">View Transactions</a>
The GridView class
Public Class HAS_Gridview
Inherits GridView
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
CellPadding = 4
GridLines = WebControls.GridLines.None
ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
ClientIDMode = UI.ClientIDMode.AutoID
With MyBase.FooterStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.White
End With
RowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#F7F6F3")
RowStyle.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
PagerStyle.HorizontalAlign = WebControls.HorizontalAlign.Center
PagerStyle.ForeColor = Color.Black
PagerStyle.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
With MyBase.SelectedRowStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
End With
With MyBase.HeaderStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.Black
.CssClass = "GridView"
End With
EditRowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#999999")
With MyBase.AlternatingRowStyle
.BackColor = Color.White
.ForeColor = Drawing.ColorTranslator.FromHtml("#284775")
.CssClass = "GridView"
End With
With MyBase.RowStyle
.CssClass = "GridView"
End With
End Sub
End Class
Have you tried adding trigger programmatically instead of registering in AjaxControlToolkit:
Dim trigger As New AsyncPostBackTrigger()
trigger.ControlID = LB.ID
trigger.EventName = "Click"
MyUpdatePanel.Triggers.Add(trigger)
It looks like the postback is caused by href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" in the generated markup for the anchor tag.
Try to define your own _doPostBack.
If you haven't checked post a and post b already, they offer a couple of ways to do that.
In the end the only way I could get this to work was
Create a class for a LinkButton Template
Public Class LinkButtonTemplate
Implements ITemplate
Private m_ColumnName As String
Event LinkButtonItem_Clicked(sender As LinkButton, e As EventArgs)
Public Property ColumnName() As String
Get
Return m_ColumnName
End Get
Set(ByVal value As String)
m_ColumnName = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal ColumnName As String)
Me.ColumnName = ColumnName
End Sub
Public Sub InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
Dim LB As New LinkButton()
With LB
.ID = "LB_" & ColumnName
.Text = ColumnName
.OnClientClick = "LinkButtonClick(this);"
End With
container.Controls.Add(LB)
End Sub
End Class
Add this javascript so that it would post the ID to a hidden field and click a hidden button
Private Sub LoadLinkButtonClick()
Try
Dim SB As New StringBuilder
SB.Append("function LinkButtonClick(LinkButton){ ")
SB.Append("setTimeout(function() { ")
SB.Append("$get('" & GridViewLBClicked.ClientID & "').click(); ")
SB.Append(" }, 300); ")
SB.Append("var sendingID = LinkButton.id; ")
SB.Append("document.getElementById('" & HiddenField1.ClientID & "').value = sendingID; ")
SB.Append("} ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "LoadLinkButton", SB.ToString, True)
Catch ex As Exception
Dim vError As New SendError
vError.MailError("1229", PageName, ex)
End Try
End Sub
On the RowDataBound event capture the ID we need and add it to the LinkButton ID (so now we know both the sending GridView and the selected row)
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
From the hidden button click we can recover all the data we need to make the async postback
Private Sub RaiseLinkButton_Click(sender As Object, e As EventArgs)
Try
Dim vFunction As New Functions
Dim vValue As String = HiddenField1.Value
Dim vSplit = vValue.Split("_")
Dim i As Integer = 0
For Count As Integer = 0 To vSplit.Length - 1
i += 1
Next
Dim DGName As String = vSplit(i - 2)
Select Case DGName
Case "AssMain"
Dim MV As MultiView = vFunction.FindControlRecursive(BodyMain, "AssessmentMultiView")
Dim GV As CustomControl.HAS_Gridview = vFunction.FindControlRecursive(BodyMain, "AssessmentDetailGV")
With GV
.DataSource = AssessmentsDetail_ReturnDataSet()
.DataBind()
.PageIndex = 0
End With
MV.ActiveViewIndex = 1
Dim vPanel As UpdatePanel = vFunction.FindControlRecursive(BodyMain, "AssessmentUpdatePanel")
vPanel.Update()
End Select
Catch ex As Exception
Dim vError As New SendError
vError.MailError("953", PageName, ex)
ShowError()
End Try
End Sub
I am using ItemTemplate & EditTemplate for editing the gridview. (ASP.net + VB).
I click EDIT button then I can check/uncheck those checkbox and amend the textbox value.
When click UPDATE button, it will fire the RowUpdating Event, But I found that when I get the value for update statement, it still get the value before editing, not updated value.
How can I get the latest & updated value ? Thanks.
Joe
The following is the VB code:
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Update the values.
Dim row = Gridview1.Rows(e.RowIndex)
Dim Col1_SL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_SL"), CheckBox)
Dim Col1_VL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_VL"), CheckBox)
Dim Col1_ML = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_ML"), CheckBox)
Dim Col1_PH = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_PH"), CheckBox)
Dim Col1_APH = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_APH"), CheckBox)
Dim Col1_TOIL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_TOIL"), CheckBox)
Dim Col1_Others = CType(Gridview1.Rows(e.RowIndex).FindControl("tb1_Others"), TextBox)
Dim Col1_RosterKey = CType(Gridview1.Rows(e.RowIndex).FindControl("lb1_rosterkey"), Label)
Using conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("hris_shiftdutyConnectionString").ConnectionString)
conn.Open()
cmd.Connection = conn
sql = "SET DATEFORMAT dmy;UPDATE troster SET SL='" & Convert.ToInt32(Col1_SL.Checked) & "' where roster_key='" & Col1_RosterKey.Text & "';"
cmd.CommandText = Sql
reader = cmd.ExecuteReader()
conn.Close()
reader.Close()
End Using
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
The most likely reason will be this.
You are calling BindData() on Page_Load without using !IsPostBack
Protected Sub Page_Load Handles Me.Load
If Not IsPostBack
' Bind Grid only at the first load
' Do not load Grid again at Postbacks
BindData()
End If
End Sub
You have 2 options:
There is a separate RowUpdated method that is fired after updates have been performed by the data source that is bound to the grid view. This method will contain the new values for edits and inserts.
The RowUpdating method should have a parameter of type GridViewEventArgs. This will have a property called NewValues that contains the new values. In your example this was the variable e.
I am creating a gridview programmatically and I want to use the solution to this question: Programmatically access GridView columns and manipulate. In other words, I want to hide the hyperlinkfield and instead display a templatefield if the value of the "submitted" column in the row is 1. I'm listing employment applications and letting the user click "Load Application" if they have not yet submitted an application, or displaying "submitted" in plain text if they have already submitted it. I know how to do this if I create my gridview in the aspx file, but I don't know how to do this when I'm creating my gridview at runtime. Here's my code:
Public Sub getSavedApps(ByVal userID As Integer)
Dim ds As New DataSet
ds = clsData.sqlGetAllApps(userID)
If ds.Tables(0).Rows.Count > 0 Then
popAppSelect.Show()
'let user select which app they want to work on
Dim grdAppSelect As New GridView
'need to find out if this row has a value of 1 or 0 for submitted
Dim submitted As Boolean
'position column
Dim fieldPosition As New BoundField
fieldPosition.DataField = "positionDesired"
fieldPosition.HeaderText = "Position Desired"
If fieldPosition.DataField.ToString = "" Then
fieldPosition.DataFormatString = "<em>No position specified</em>"
End If
Dim colPosition As DataControlField = fieldPosition
'date column
Dim fieldDate As New BoundField
fieldDate.DataField = "dateStarted"
fieldDate.HeaderText = "Date Started"
Dim colDate As DataControlField = fieldDate
Dim strAppID(0) As String
strAppID(0) = "appID"
Dim colLoad As DataControlField
'submitted column
If submitted Then
Dim fieldLoad As New TemplateField
fieldLoad.ItemTemplate = New GridViewTemplate(DataControlRowType.DataRow, "submitted")
colLoad = fieldLoad
Else
Dim fieldLoad As New HyperLinkField
fieldLoad.Text = "<b>Load Application »</b>"
fieldLoad.DataTextFormatString = "{0}"
fieldLoad.DataNavigateUrlFields = strAppID
fieldLoad.DataNavigateUrlFormatString = "?load={0}"
colLoad = fieldLoad
End If
'add the columns to the gridview
With grdAppSelect
.ID = "grdAppSelect"
.CssClass = "grdAppSelect"
.CellPadding = 5
.BorderWidth = "0"
.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
With .Columns
.Add(colPosition)
.Add(colDate)
.Add(colLoad)
End With
.AutoGenerateColumns = False
.DataSource = ds.Tables(0)
.DataBind()
End With
Dim lnkNew As New HyperLink
lnkNew.Text = "<b>Start New Application »</b>"
lnkNew.NavigateUrl = "?load="
Dim strClear As New LiteralControl
strClear.Text = "<br class='clearer' />"
'add the controls to the panel
pnlAppSelect.Controls.Add(grdAppSelect)
pnlAppSelect.Controls.Add(strClear)
'pnlAppSelect.Controls.Add(lnkNew)
Else
'should be apps there but couldn't find them
lblGeneralError.Text = "Could not find any previously started applications."
End If
End Sub
I found the solution. I needed to add an event handler when I created the gridview so that I could access the RowDataBound event and do the evaluation there. Here's the event handler code I used:
AddHandler grdAppSelect.RowDataBound, AddressOf grdAppSelect_RowDataBound
Then I just did my evaluation during RowDataBound like so:
Sub grdAppSelect_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim load As Control = e.Row.Controls(2)
Dim submitted As Control = e.Row.Controls(3)
Dim submittedText As String = e.Row.Cells(3).Text
If submittedText = "True" Then
load.Visible = False
End If
submitted.Visible = False
End If
End Sub