Add click event to dynamic button inside calendar - asp.net

I have a calendar control in my website (vb.net in asp.net)(the standard calendar control but I manipulated it and now it looks like outlook calendar)
The events are added to the calendar as dynamic buttons, and each button has uniqe ID which is the same even after postback.
This is my code to generate the button and add it to the appropiate cell in calendar:
Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender
Dim nextDate As DateTime
If Not dsHearings Is Nothing Then
For Each dr As DataRow In dsHearings.Tables(0).Rows
nextDate = CType(dr(6), DateTime)
If nextDate = e.Day.Date Then
e.Cell.BackColor = System.Drawing.Color.LightGoldenrodYellow
Dim btn As New Button
btn.Text = Left(dr(7).ToString, 5) & "-" & "جلسة في ملف" & dr(1) & " " & dr(2) & " (" & dr(8) & ")"
btn.CssClass = "CalendarHearingEvent"
btn.BackColor = Drawing.Color.Red
btn.ToolTip = "جلسة في ملف" & dr(1) & " " & dr(2) & " (" & dr(8) & ")"
btn.ID = "btnHearings" & dr(9).ToString
btn.UseSubmitBehavior = True
AddHandler btn.Click, AddressOf Me.HearingButton_Click
Dim lbl As New Label
lbl.Text = "<br>"
e.Cell.Controls.Add(lbl)
e.Cell.Controls.Add(btn)
End If
Next
End If
And this is the Handling sub:
Private Sub HearingButton_Click(sender As Object, e As EventArgs)
End Sub
Everything is perfect, but the click event not firing
Please Help

I used LinkButton, and have set href property of link button to
lnkButton.Attributes("href") = e.SelectUrl
Code
lnkButton = New LinkButton()
lnkButton.CommandArgument = objScheduleDetail.SelectedDate
lnkButton.Text = <Write your text here>
lnkButton.ID = "lnkView" ' you can make it unique as well
lnkButton.Attributes("href") = e.SelectUrl
e.Cell.Controls.Add(lnkButton)
Now when this link button is clicked Calendar.SelectionChanged event is fired. and I use Calendar1.SelectedDate to get the date of the clicked button.
Protected Sub Calendar1_SelectionChanged(sender As Object, e As System.EventArgs) Handles Calendar1.SelectionChanged
Calendar1.SelectedDate ' date which is clicked.
End Sub

Thanks danish for your answer, but I need also to pass arguments. so I used your answer with extra code to meet the needs of my app.
The problem is that when a dynamic button inside calendar is clicked, it posts back the calendar event and not the button click event, so the app is not catching the button.
To bypass that, In my code behind I generated a linkbutton like this:
Dim btn As New LinkButton
btn.Text = "Text On LinkButton"
btn.CssClass = "CalendarEvent"
btn.ToolTip = "What ever"
btn.ID = "LinkButton1"
Dim str As String = "return EventonMyClientClick(" + dr(0).ToString + ");"
btn.OnClientClick = str
e.Cell.Controls.Add(btn)
This will generate a linkbutton inside calendar cell with OnClientClick pointing to a javascript function in HTML Code which goes like this:
<asp:LinkButton ID="LinkButton1" style="display:none;" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
<asp:HiddenField ID="hdEventSentId" runat="server" />
<script>
function EventonMyClientClick(val) {
document.getElementById('<%=hdEventSentId.ClientID%>').value = val;
var btn = document.getElementById('<%=LinkButton1.ClientID%>');
btn.click();
}
</script>
As you see, The dynamic linkbutton passes my argument (dr(0).ToString) to eventonmyclientclick function. the function gets the argument, saves it in the hiddenfield and then perform a click event for the linkbutton1 linkbutton.
the page posts back and catches the linkbutton1 click event, which calls the code behind handler of the linkbutton that handles the argument saved in the hiddenfield:
Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)
Try
Dim EventId As String = hdEventSentId.Value
....
Catch ex As Exception
End Try
End Sub
I hope this will help others seeking for a solution for the same problem.

Related

OnClick function on dynamic LinkButton?

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?

how to check selected item in Check Box List (generated from code)

i have I have an ASP.NET / VB application
i need check on selected item in check box list but the checkbox is dynamically from code behind
<asp:Panel ID="panel1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Save" />
<asp:Label ID="lbl_Selected_Items" runat="server" Text=""></asp:Label>
</asp:Panel>
code behind
page load
Dim CheckBoxList As New CheckBoxList
pagerview.Controls.Add(CheckBoxList)
...est
Button1 Click event
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CheckBoxList1 As CheckBoxList = CType(Me.FindControl("CheckBoxList"), CheckBoxList)
Dim sCheckedValue As String = ""
For Each oItem As ListItem In CheckBoxList1.Items
If oItem.Selected Then
If sCheckedValue = "" Then
sCheckedValue = ("Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
Else
sCheckedValue += ("<br/>Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
End If
End If
Next
lbl_Selected_Items.Text = sCheckedValue
error text : null reference exception object reference not set to an instance of an object –
Error
So what is happening? Error? no result?
At this point the only thing I can recommend is loading dynamic controls in the page init instead of the page load.
EDIT
You will find when you debug that your checkbox on the first line of your button click is Nothing. There are two mistakes in your code.
When you add the control to the form, you do not provide an id value. and you do not lookup this value
When you lookup the control in the button click FindControl only looks in a single container. It is not recursive. You should be calling pagerView.FindControl
The Page load (I still recommend init):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Handles Me.Load
Dim CheckBoxList As New CheckBoxList
CheckBoxList.ID = "cbl1"
pagerview.Controls.Add(CheckBoxList)
End Sub
And the button click:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CheckBoxList1 As CheckBoxList = CType(pagerview.FindControl("cbl1"), CheckBoxList)
Dim sCheckedValue As String = ""
For Each oItem As ListItem In CheckBoxList1.Items
If oItem.Selected Then
If sCheckedValue = "" Then
sCheckedValue = ("Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
Else
sCheckedValue += ("<br/>Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
End If
End If
Next
lbl_Selected_Items.Text = sCheckedValue
End Sub
MS Reference

GridView Double-click Event in Asp.Net

I am using a GridView control in ASP.NET web form to display the data records. I want to handle the double click event of the row of the GridView. also I should get information which row is clicked.
Please refer to this brilliant post that will assist you with your problem
http://www.codeproject.com/Articles/15677/Clickable-and-Double-Clickable-Rows-with-GridView
Protected Sub GridView2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
Dim i As Integer = 0
GridView1.Rows(row.RowIndex).BackColor = ColorTranslator.FromHtml("#A1DCF2")
MsgBox(doubleClick & " " & GridView1.SelectedIndex.ToString)
If doubleClick = GridView1.SelectedIndex.ToString Then
MsgBox("Yo")
End If
doubleClick = GridView1.SelectedIndex.ToString
End Sub
Try this simple code I wrote. It works for me.
Protected Sub GridView2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
Dim i As Integer = 0
GridView1.Rows(row.RowIndex).BackColor = ColorTranslator.FromHtml("#A1DCF2")
MsgBox(doubleClick & " " & GridView1.SelectedIndex.ToString)
If doubleClick = GridView1.SelectedIndex.ToString Then
MsgBox("Yo")
End If
doubleClick = GridView1.SelectedIndex.ToString
End Sub
After a lot of unsuccessful tries, I got it done using Jquery, this way:
$('html').on('click', ".wwdblclick", function (e) {
e.preventDefault;
return false;
});
$('html').on('dblclick', ".wwdblclick", function (e) {
var x = $(this).attr("href").replace("javascript:", "");
$(this).attr("ondblclick", x);
if (!(typeof $(this).attr("wwRunningDblclick") !== "undefined")) {
$(this).attr("wwRunningDblclick", "true");
$(this).trigger("dblclick");
}
else {
$(this).removeAttr("wwRunningDblclick");
}
});
Then just set the "wwdblclick" cssClass in your grid button command, like this:
<asp:LinkButton ID="lkbX" runat="server" Text="<i class=icon-minus-sign></i>" CssClass="wwdblclick" CommandName="action" CommandArgument='<%# Eval("id") %>' />
Cheers,
You can try with RowCommand
http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.gridview.rowcommand%28v=vs.80%29.aspx

adding linkbutton dynamilcy to gridview. not firing.

I am dynamically adding a link button to every cell in a gridview. Adding the button works however the firing of the even handler doesn't. i need the linkbutton to call a function and pass some data for processing. My code is below. I have found solutions from the site that have gotten me this far.
At the moment the gridview loads the cells with buttons in blue. when you click them they go back to plain text and no function is called.
Private Sub gv_datasource_options_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv_datasource_options.RowDataBound
Try
If e.Row.RowType = DataControlRowType.DataRow Then
For Each c As TableCell In e.Row.Cells
If Len(c.Text) > 0 And c.Text <> " " Then
Dim v_lb As New LinkButton()
v_lb.Text = c.Text
AddHandler v_lb.Click, AddressOf add_datasource
v_lb.Attributes.Add("AutoPostback", "True")
v_lb.Attributes.Add("runat", "Server")
v_lb.Attributes.Add("AutoEventWireup", "True")
v_lb.CommandName = "NumClick"
v_lb.CommandArgument = e.Row.Cells(0).ToString & "|" & gv_datasource_options.HeaderRow.Cells(e.Row.Cells.GetCellIndex(c)).Text
c.Controls.Add(v_lb)
Dim sm As ScriptManager = ScriptManager.GetCurrent(Me)
sm.RegisterAsyncPostBackControl(v_lb)
End If
Next
End If
Catch ex As Exception
cl_Error.cl_Erorr.LogError(ex, txt_userid.Value, ex.ToString)
End Try
End Sub
Private Sub add_datasource(sender As Object, e As CommandEventArgs)
Try
hf_datasource_id.Value = Left(e.CommandArgument.ToString(), (Len(e.CommandArgument.ToString) - InStr(e.CommandArgument.ToString, "|")))
hf_datasource_column.Value = Left(e.CommandArgument.ToString(), (Len(e.CommandArgument.ToString) - InStr(e.CommandArgument.ToString, "|")))
hf_datasource_tableid.Value = tv_content.SelectedValue
p_datasource.Visible = False
Catch ex As Exception
cl_Error.cl_Erorr.LogError(ex, txt_userid.Value, ex.ToString)
End Try
End Sub
Rather than adding Event ("add_datasource") to Linkbutton, trying using GridView's RowCommand Event. You will surely be able to fetch the event bubbled by linkbutton on Gridview's Row Command Event (along with the commandname and commandarguments)

My rowcommand has no command name for my gridview

I have an image button that is created on rowcreated manually in code.
Dim deletecshr As New ImageButton
deletecshr.ImageUrl = "\images\bttnDeletemini.gif"
deletecshr.ToolTip = "This Will Delete All Cashiers"
deletecshr.ID = "deletecshr"
In gridveiw_rowdatabound I have the following:
Dim deletecshr As ImageButton = DirectCast(e.Row.FindControl("deletecshr"), ImageButton)
deletecshr.CommandName = "Delete"
deletecshr.CommandArgument = emp_no & "," & e.Row.Cells(2).Text & "," & e.Row.Cells(1).Text & "," & cashier_no & "," & manager_no
I set the commandname and the argument.
However, in rowcommand it finds no commandname or anything else. What am i doing wrong? I believe this has worked before.
From what i can tell you never attach the event.
Dim deletecshr As New ImageButton
deletecshr.ImageUrl = "\images\bttnDeletemini.gif"
deletecshr.ToolTip = "This Will Delete All Cashiers"
deletecshr.ID = "deletecshr"
AddHandler deletecshr.Command AddressOf deletecshrCommandEventHandler
You'll have a method similar of this in your code:
Protected Sub deletecshrCommandEventHandler(sender As Object, e As CommandEventArgs)
If e.CommandName = "Delete" Then
'Do your stuff
End IF
End Sub
EDIT
Added some more code and fixed a small syntax error.

Resources