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
Related
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.
This has got to be the simplest question ever. Im trying to use a link button with the "postbackurl" to post a value to another page. It works with a button, but it is blank with a linkbutton. I dont want to use querystring. Any ideas?
default.aspx:
<asp:LinkButton ID="LinkButton" postbackurl="~/2.aspx" Text="ThisIsATest" runat="server">ThisIsATest</asp:LinkButton>
2.aspx:
Dim test = Request.Form("LinkButton")
Response.Write(test)
Try with this code
var text = ((LinkButton)PreviousPage.FindControl("LinkButton")).Text;
Use PreviousPage.FindControl to get the control reference
Dim lb As LinkButton = DirectCast(PreviousPage.FindControl("LinkButton"), LinkButton)
If lb IsNot Nothing Then
Response.Write(test.ID) ' display linkbutton ID
Response.Write(test.Text) ' display linkbutton Text
End If
Try:
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton1.Click
Response.Redirect("2.aspx?id=" + somestring)
End Sub
I have a Telerik RadGrid with a GridTemplateColumn that contains a checkbox, as follows:
<telerik:GridTemplateColumn HeaderText="MINE" UniqueName="MyTemplateColumn">
<ItemTemplate>
<asp:CheckBox id="MyCheckBox" runat="server"></asp:CheckBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
I want to set the box to be "checked" based on a value read from the database. I could handle the ItemDataBound event and read the database when each row is bound, but that results in n lookups. Instead, I want to handle DataBound, and then set all the values at once. So, in that method, I want code like this:
// read all values from database first, then...
foreach(var chkbox in MyRadGrid.MasterTableView.Columns.FindByUniqueName("MyTemplateColumn").FindControl("MyCheckBox")) {
chkbox.Checked = oneValue;
}
That doesn't work, because FindControl isn't a method of GridColumn, and it won't generate an iterable list of the checkboxes. What is the correct way to iterate through the checkboxes in the template column? Thanks!
Telerik got back to me on their forums with the answer, as follows:
foreach (GridDataItem item in MyRadGrid.MasterTableView.Items)
{
CheckBox chk = (CheckBox)item.FindControl("MyCheckBox");
// Set the value here
}
Hope this is useful for someone!
I am having the same issue.. this was how I did it..
'Created a local hashtable to use now and otherwise
Private _GroupMembers As New Hashtable
'Loaded it up on page load
Private Function GetMembers() As Boolean
Try
Dim da As New DataAccess
Dim ht As New Hashtable
Dim i As Int16 = 0
ht.Add("CAC", Session("cac"))
ht.Add("GroupID", _GroupID)
If da.GetData("rap_spGetGroupMemberList", ht) = True Then
If da.SQLDataRows.HasRows Then
While da.SQLDataRows.Read()
i = i + 1
_GroupMembers.Add(i, da.SQLDataRows("UserID"))
End While
End If
da.SQLDataRows.Dispose()
End If
da = Nothing
Catch ex As Exception
Console.Write(ex.Message)
End Try
End Function
'Check for contains
Protected Sub RadGrid2_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid2.ItemDataBound
Try
If e.Item.IsDataBound Then
If Not e.Item.DataItem("UserID") Is Nothing Then
If Not IsDBNull(e.Item.DataItem("UserID")) Then
Dim UserID As Long = e.Item.DataItem("UserID")
If _GroupMembers.ContainsValue(UserID) Then
e.Item.Selected = True
End If
End If
End If
End If
Catch ex As Exception
Console.Write(ex.Message)
End Try
End Sub
I am trying to access a control inside a Repeater. The control is inside the <ItemTemplate> tag. I am using FindControl but it's always coming out Null.
What am I doing wrong?
My guess is that FindControl can only be used in record-level events such as ItemDataBound:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
(ControlTypeCast) e.Item.FindControl("myControl")).SomeProperty = "foo";
}
I'm guessing that you're trying to find a control at the wrong point in the page lifecycle. The ItemDataBound event is where you need to look for it.
This example is in vb.net, but I'm sure you get the idea.
Protected Sub rp_items_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rp_items.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim someLiteral As Literal = e.Item.FindControl("someliteral")
End If
End Sub
In most cases, spelling the control name wrong :) It may also be that you are searching for a control that exists within another container. Can you post your code?
for (int i = 0; i <= repeater1.Items.Count - 1; i++)
{
Button delete = (Button)repeater1.Items[i].FindControl("btnDelete");
delete.Visible = true;
Button edit = (Button)repeater1.Items[i].FindControl("btnEdit");
edit.Visible = true;
}
Vb.net
For i As Integer = 0 To Repeater1.Items.Count - 1
Dim CmbTyp As DropDownList = DirectCast(Repeater1.Items(i).FindControl("DropDownList1"),DropDownList)
Dim SeatN As Label = DirectCast(Repeater1.Items(i).FindControl("label1"), Label)
styp = CmbTyp.SelectedItem.Text.Trim
sNo = SeatN.Text
Next
Try This
For vb.net
CType(e.Item.FindControl("myControl"), Literal).Text = "foo"
For c#
[Literal]e.item.FindControl["myControl"].Text="foo";
Classic scenario: Take user input, get a search-result and display it in pages to the user. I then need to display buttons for First, Next, Previous etc, and I maintain the users current page in viewstate. All is good, works fine.
Then I need to implement clickable page numbers, ie. 1-2-3-4-5-6 etc.
Rendering them is simple. I generate a linkbutton control at runtime, add commandargument with the page number and add a handler to it, so click are to be handled. Then I add it to a placeholder, and it is displayed as expected.
But then... If I did not already have a shaved head, I would be pulling out my hair getting the events to fire as expected every time.
How should I do this, so my events are always wired up and able to fire when the paging-linkbuttons are called?
Below is the important parts of the code, some pseudo to make it (hopefully) easier to understand, what I am doing.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Search()
End If
End Sub
Sub Search
'Misc databinding stuff, searches and displays results for the page specified in Me.CurrentPage
RenderPagingControls()
End Sub
Sub RenderPagingControls
'loop throug pagenumbers, Build a linkbutton control, add it to a placeholder
AddHandler lbn.Click, AddressOf lbnNumber_Click
lblPageNumbers.Controls.Add(lbn)
...
End Sub
Protected Sub lbnNumber_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim b As LinkButton = CType(sender, LinkButton)
Me.CurrentPage = CInt(b.CommandArgument)
Search()
End Sub
Public Property CurrentPage() As Integer
Get
Dim o As Object = Me.ViewState("CurrentPage")
If o Is Nothing Then
Return 1
Else
Return CType(o, Integer)
End If
End Get
Set(ByVal value As Integer)
Me.ViewState("CurrentPage") = value
End Set
End Property
Protected Sub lbnNumber_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim b As LinkButton = CType(sender, LinkButton)
Me.CurrentPage = CInt(b.CommandArgument)
Search()
End Sub
I'm going to recommend against a LinkButton and recommend Hyperlinks / QueryString parameters instead. For several reasons:
Your page will be much more efficient without the viewstate overhead of a link button.
If these are public facing pages, you'll get better indexing of all the pages if they can be accessed via hyperlinks (and indexed via search engines).
You'll find them much easier to implement. No event management, etc.
You would redefine your CurrentPage method as (hopefully this is correct, I'm better at C# than vb.net):
Public Property CurrentPage() As Integer
Get
Dim o As Object = Me.Request.QueryString("page")
If o Is Nothing Then
Return 1
Else
Return CType(o, Integer)
End If
End Get
End Property
Then just add hyperlinks for each page.
<a href='mypage.aspx?page=1'>1</a> - <a href='mypage.aspx?page=2'>2</a>
etc...
Alternative: If you want to use the LinkButton, you might want to consider putting a single LinkButton in a repeater. Then the only event you have to worry about is the OnItemCommand event. Then no dynamic controls or events. Something like this:
<asp:Repeater ID="rptPages" runat="server" OnItemCommand='doPaging'>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# (Container.DataItem).ToString() %>'
CommandArgument='<%# (Container.DataItem).ToString() %>' />
</ItemTemplate>
<SeparatorTemplate>-</SeparatorTemplate>
</asp:Repeater>
Bind this control to an array (or list) of consecutive Integers (as many are there are pages). Then in your doPaging function (as I call it), check RepeaterCommandEventArgs.CommandArgument to get the page number.
Thanks for the answers, guys. I tried out Austins first, but I must be missing something, because I keep getting the same behavior of link buttons only working every second time... So I gave up on that, and saw the alternative solution with the repeater by Keltex! It is as brilliant as it is simple, and we don't have to worry about any page life-cycle bullshit.
It just really works! ;)
If somebody should need something similar in the future, here is the relevant code behind the scenes:
Sub Search()
...
RenderPagingControls()
End Sub
Sub RenderPagingControls()
Dim pages As New ArrayList
For i As Integer = 1 To Me.PageCount
pages.Add(i)
Next
repPageNumbersTop.DataSource = pages
repPageNumbersTop.DataBind()
repPageNumbersBottom.DataSource = pages
repPageNumbersBottom.DataBind()
End Sub
Public Property CurrentPage() As Integer
Get
Dim o As Object = Me.ViewState("CurrentPage")
If o Is Nothing Then
Return 1
Else
Return CType(o, Integer)
End If
End Get
Set(ByVal value As Integer)
Me.ViewState("CurrentPage") = value
End Set
End Property
Public Property PageCount() As Integer
Get
Dim o As Object = Me.ViewState("PageCount")
If o Is Nothing Then
Return 0
Else
Return CType(o, Integer)
End If
End Get
Set(ByVal value As Integer)
Me.ViewState("PageCount") = value
End Set
End Property
Protected Sub repPageNumbersTop_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles repPageNumbersTop.ItemCommand, repPageNumbersBottom.ItemCommand
Me.CurrentPage = CType(e.CommandArgument, Integer)
Search()
End Sub
Private Sub repPageNumbersTop_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles repPageNumbersTop.ItemDataBound, repPageNumbersBottom.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim lbn As LinkButton = CType(e.Item.FindControl("lbnPageNumber"), LinkButton)
If lbn.CommandArgument = Me.CurrentPage.ToString Then
lbn.Enabled = False
End If
End If
End Sub
This code works (sorry it's in C#):
protected void SearchButton_Click(object sender, EventArgs e)
{
//clear the collection!
pnlPageNumber.Controls.Clear();
//simulate search
System.Random rnd = new Random();
//create page buttons
for (int i = 0; i < rnd.Next(3, 15); i++)
{
LinkButton lb = new LinkButton();
pnlPageNumber.Controls.Add(lb);
lb.ID = "btn" + i;
lb.Text = i.ToString();
lb.CommandArgument = i.ToString();
lb.Command += new CommandEventHandler(linkbutton_Command);
//optional literal
pnlPageNumber.Controls.Add(new LiteralControl(" "));
}
ViewState["control#"] = Panel1.Controls.Count;
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//Recreate link buttons
//This is necessary to ensure proper event binding
int count = 0;
if (ViewState["control#"] != null)
count = (int)ViewState["control#"];
for (int i = 0; i < count; i++)
{
LinkButton lb = new LinkButton();
pnlPageNumber.Controls.Add(lb);
lb.ID = "btn" + i; //make sure IDs are the same here and on Search
lb.Command += new CommandEventHandler(linkbutton_Command);
//this is not necessary, but if you do, make sure its in both places
pnlPageNumber.Controls.Add(new LiteralControl(" "));
}
}
}
void linkbutton_Command(object sender, CommandEventArgs e)
{
Response.Write(e.CommandArgument.ToString() + " CLICK<br />");
}
You could use the DataPager control -- the only limitation is you have to use it with the ListView control, but you should be able to represent your data using the ListView control fairly easily because it is very flexible. You can set the DataSource of the ListView control to the result of your data result, whether that be a DataSet, Collection, Array, etc.
To create the paging controls with "first", "last", and page numbers, set up the DataPager like this (where ListView1 is the ID of your ListView control):
<asp:DataPager ID="DataPager1" runat="server"
PagedControlID="ListView1" PageSize="25">
<Fields>
<asp:NextPreviousPagerField FirstPageText="first" ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="False" />
<asp:NumericPagerField />
<asp:NextPreviousPagerField LastPageText="last" ShowLastPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="False" />
</Fields>
</asp:DataPager>
By design, the DataPager uses the whole result set from the database, but you can improve the performance by caching the result and using that on the subsequent requests.
Hope this helps.
iirc... adding controls dynamically at runtime is a bit tricky. The control tree must be rebuilt during post back... but before viewstate is loaded (not sure when in the page life cycle... but way before page load). So... your problem is that by the time asp.net is trying to figure out your event the actual originating control has not yet been created.