How to get Command Functionality from a Panel - asp.net

Is there a Panel or any container with CommandName, CommandArguments instead of using Buttons (LinkButton, ImageButton, ...)?
I want to add a column in a GridView to make selection for the row, the whole cell's rectangle instead of a Select link.

You can make (almost) anything implement CommandName and CommandArguments by implementing the IButtonControl interface. You will probably also want to implement the IPostBackEventHandler interface.
This article covers in detail exactly what you are asking about, generally: making a Panel into a command control. It's not entirely trivial.
But making a table row clickable is a lot easier, though, esp. using jQuery. See this article. You just bind an event to the row, and go from there. In this example, they're redirecting to the url for a link in the row on a click event. You could just as easily do something else like call __doPostBack to cause an async postback and run arbitrary server code, e.g.

Here is another way how you can make a GridView-Cell as Sort-Column(see in RowCreated, the rest is sample-data):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
If Not IsPostBack Then
BindGridView()
End If
End Sub
Private Sub BindGridView()
Dim source As New List(Of String)(New String() {"1. row", "2. row", "3. row", "4. row", "5. row"})
Me.GridView1.DataSource = source
Me.GridView1.DataBind()
End Sub
Private Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated
Dim cell As New TableCell
If e.Row.RowType = DataControlRowType.DataRow Then
cell.Text = "select"
cell.ToolTip = "click to select row"
cell.Attributes("onmouseover") = "this.style.cursor='pointer';"
cell.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(DirectCast(sender, GridView), "Select$" & e.Row.RowIndex)
End If
e.Row.Cells.Add(cell)
End Sub
Edit: if you get a "Invalid postback or callback argument"-Exception from ASP.Net, you can either set EnableEventValidation="False" or add following to your page's codebehind:
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
ClientScript.RegisterForEventValidation(GridView1.UniqueID, "Select$" & row.RowIndex)
End If
Next
MyBase.Render(writer)
End Sub
If you need C#, copy all into: http://www.developerfusion.com/tools/convert/vb-to-csharp/

Related

Failure to update textbox.text

I have a relatively simple ASP.NET problem (I should think) that regrettably I am unable to solve by myself. What I am trying to do is the following:
On a page I load a number of controls (Text Boxes) programmatically;
following this load the user should be able to select a value to load into the Textbox from a panel control that is added to the page following the click of a button
Once the panel is closed, the selected text from the panel should be loaded into the textbox
However, in the vb.net statements below when run the "test" string never makes it to the textbox - any help with resolving this would be greatly appreciated.
Public Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Controls_Load()
End Sub
Public Sub Controls_Load()
Dim ttf_tb As New TextBox With {.ID = "ttf_tb"}
Master_Panel.Controls.Add(ttf_tb)
Dim ttf_button As New Button
Master_Panel.Controls.Add(ttf_button)
AddHandler ttf_button.Click, AddressOf TTF_BUTTON_CLICK
End Sub
Public Sub TTF_BUTTON_CLICK(sender As Object, e As EventArgs)
Dim str As String = sender.id
Dim panel As New Panel
panel.ID = "TTF_Panel"
panel.Width = 300
panel.Height = 300
Master_Panel.Controls.Add(panel)
panel.BackColor = Drawing.Color.Black
panel.Style.Add(HtmlTextWriterStyle.Position, "absolute")
panel.Style.Add(HtmlTextWriterStyle.Left, "200px")
panel.Style.Add(HtmlTextWriterStyle.Top, "100px")
panel.Style.Add(HtmlTextWriterStyle.ZIndex, "100")
Dim CL_Button As New Button
CL_Button.ID = "TTF_Close_" & Replace(str, "TTF_Button_", "")
panel.Controls.Add(CL_Button)
AddHandler CL_Button.Click, AddressOf TTF_Close_Button_Click
End Sub
Public Sub TTF_Close_Button_Click(sender As Object, e As EventArgs)
Dim ttf_tb As TextBox = Master_Panel.FindControl("ttf_tb")
ttf_tb.Text = "Test"
Dim panel As Panel = FindControl("TTF_Panel")
Master_Panel.Controls.Remove(panel)
End Sub
End Class
I think you need to re-create your controls in the Page_Init method. It's been a while since I've done web forms but I think it's something like:
When a user clicks the button a post back is fired. This re-creates a new instance of your class, creates the controls on the page, assigns any form values then calls your Page_Load event.
The problem is you are creating your controls too late, so the forms values are never assigned correctly.
You should create / recreate your dynamic controls in the Init event:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Controls_Load()
End Sub
This should allow you to maintain their state across PostBacks.
For more information about this topic, see the MSDN article on the ASP.NET Page Life Cycle.

How to switch back to EditTemplate after an Update to ItemTemplate in a ListView

It have a ListView with LayoutTemplate, ItemTemplate and EditTemplate. The List view only ever shows one item.
The ItemTemplate as an EditButton with CommandName = 'Edit' which when clicked triggers...
Protected Sub ListView1_ItemEditing(ByVal sender As Object, ByVal e As ListViewEditEventArgs) Handles ListView1.ItemEditing
ListView1.EditIndex = e.NewEditIndex
'Create SQL and load result in datatable and bind to listview
LoadData(Session("SID"))
End Sub
The EditTemplate has an UpdateButton with CommandName 'Update' which when clicked triggers...
Protected Sub ListView1_Command(ByVal sender As Object, ByVal e As ListViewCommandEventArgs) Handles ListView1.ItemCommand
If e.CommandName = "Update" Then
'Use StringBuilder to build up an UPDATE TSql script
SqlStr = sb.ToString
'Execute Update
ExecuteSQLScript(SqlStr)
End If
The above works great. My question is how do I now get back to ItemTemplate View. I know that I must use the ItemUpdating method similar to the way the above ItemEditing method worked, but I've ran out of ideas... Any help appreciated. All I have at the moment is...
Protected Sub ListView1_Updating(ByVal sender As Object, ByVal e As ListViewUpdateEventArgs) Handles ListView1.ItemUpdating
'ListView1.ItemIndex = e.ItemIndex 'This does not work
LoadData(Session("SID"))
End Sub
Thanks
Set the EditIndex to -1.
ListView1.EditIndex = -1

button add event click event

I have a button within a formview control on my page.
Because the button is contained within the formview, my code-behind can't see it.
So I did this:
Dim btnSave As Button = CType(fvCourse.FindControl("btnSave"), Button)
And then I added an event handler like this:
AddHandler btnSave.Click, AddressOf btnSave_Click
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Response.write("hey!")
End Sub
The problem is, I don't think it's working because I never see the "hey!" on my page.
Am I missing something?
Thanks
I don't know about missing something, but I reckon you could do it a simpler way since you're using VB. Give your button a command name and command argument first:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
CommandArgument="1" CommandName="yes" />
These can be anything - typically you use the command name to determine which button a user clicked on, and the command argument to show the record id.
In your code-behind, attach a macro to the ItemCommand event of the FormView (which fires when something happens within it):
Protected Sub FormView1_ItemCommand(sender As Object, e As System.Web.UI.WebControls.FormViewCommandEventArgs) Handles FormView1.ItemCommand
Select Case e.CommandName.ToLower
Case "yes"
'test
Label2.Text = "You chose " & e.CommandArgument.ToString
End Select
End Sub Protected Sub FormView1_ItemCommand(sender As Object, e As System.Web.UI.WebControls.FormViewCommandEventArgs) Handles FormView1.ItemCommand
Select Case e.CommandName.ToLower
Case "yes"
'test
Label2.Text = "You chose " & e.CommandArgument.ToString
End Select
End Sub
And in VB, that's all you need to do!
You should use the ItemCreated event of the FormView for such things. If the Button is in the ItemTemplate you need to check for the FormViewMode.ReadOnly, for EditItemTemplate you need to use Edit:
Private Sub fvCourse_ItemCreated(ByVal sender As Object, ByVal e As System.EventArgs) Handles fvCourse.ItemCreated
Select Case fvCourse.CurrentMode
Case FormViewMode.Edit
Dim btnSave As Button = DirectCast(fvCourse.FindControl("btnSave"), Button)
AddHandler btnSave.Click, AddressOf btnSave_Click
End Select
End Sub

Dynamic link button not firing in update panel

I'm dynamically adding a link button in the footer of a grid view. The grid view is wrapped in an update panel. I can get an async post back (I can tell by seeing an update progress flash), but I can't get the debug point in my click function to fire.
Private Sub gvParts_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvParts.RowDataBound
ElseIf e.Row.RowType = DataControlRowType.Footer Then
If _showPrice Then
Dim clearbutton As New LinkButton
clearbutton.ID = "btnClearCart"
clearbutton.Text = "Remove All"
ScriptManager1.RegisterAsyncPostBackControl(clearbutton)
e.Row.Cells(7).Controls.Add(clearbutton)
AddHandler clearbutton.Command, AddressOf clearButton_click
End If
End If
Private Sub clearButton_click(ByVal sender As Object, ByVal e As System.EventArgs)
ClearCart()
End Sub
try this
<dl>
Private Sub gvParts_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvParts.RowDataBound
ElseIf e.Row.RowType = DataControlRowType.Footer Then
If _showPrice Then
Dim clearbutton As New LinkButton
clearbutton.ID = "btnClearCart"
clearbutton.Text = "Remove All"
ScriptManager1.RegisterAsyncPostBackControl(clearbutton)
e.Row.Cells(7).Controls.Add(clearbutton)
AddHandler clearbutton.Command, AddressOf clearButton_click
ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(clearbutton)
End If
End If
Sorry,It's my mistake I have posted wrong code.Place the above code on OnRowCreated event of gridview
try this
Private Sub gvParts_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvParts.RowDataBound
ElseIf e.Row.RowType = DataControlRowType.Footer Then
If _showPrice Then
Dim clearbutton As New LinkButton
clearbutton.ID = "btnClearCart"
clearbutton.Text = "Remove All"
ScriptManager1.RegisterAsyncPostBackControl(clearbutton)
e.Row.Cells(7).Controls.Add(clearbutton)
AddHandler clearbutton.Command, AddressOf clearButton_click
ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(clearbutton)
End If
End If
The controls have to be added to your Controls collection prior to the page_load event. The default databinding (which fires the OnRowCreated, OnRowDataBound events) happens during the OnLoad event. Try moving your databinding code to the Page_Init function. Depending on what your databinding code looks like, this might mean you will have to implement the databinding "manually" (ie. Set the datasource and call .DataBind() in code)

Send parameter to addhandler?

I have a button in a grid that I created programmatically. The button edits some data in a table using data in a hidden column of the grid that the button is in. Normally I send a hidden field the row data using javascript onclientclick of the button then make the changes to the database using that hidden field. But there must be a way to send the addhandler of the button a parameter. This is the code i have to clarify....
Dim btnedit As New ImageButton
AddHandler btnedit.Click, AddressOf btnedit_Click
btnedit.ImageUrl = "\images\bttnEditMini.gif"
If e.Row.RowType <> DataControlRowType.Header And e.Row.RowType <> DataControlRowType.Footer Then
e.Row.Cells(3).Controls.Add(btnedit)
End If
here is my Addhandler with its delegate:
Public Delegate Sub ImageClickEventHandler(ByVal sender As Object, ByVal e As ImageClickEventArgs)
Sub btnedit_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
//programming stuff
End Sub
How can i send this handler a parameter?
By convention, all event handlers accept two parameters: the sender, and the EventArgs. If you need to send custom information to the listeners, create a new class that inherits from EventArgs and contains the information that you need to communicate.
Check out this article on CodeProject that shows you how to do this.
Short answer: no. Where would you send it? You've got two parameters.
Longer answer: sender is the control that sent the event. In this case, it will be your btnEdit control. Maybe that will help you.
Since it was in a grid i just used the row command instead. And when Row command is used you can send it a commandname and a commandargument. I passed my parameter as the argument.
GridView1.Rows(i).Cells(3).Controls.Add(btndel)
btndel.ImageUrl = "\images\bttnDelete.gif"
btndel.ToolTip = "This will delete the Selected Assignment"
btndel.CommandName = "destroy"
btndel.CommandArgument = GridView1.Rows(i).Cells(0).Text
btndel.Attributes.Add("onclick", "javascript: if(confirm('Are you sure you want to delete this Department Cost Days Assignment?')==false) return false;")
here is the rowcommand:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "destroy" Then 'used destroy because Delete command was prohibited.
Call Connection()
Dbcmd.CommandText = "Delete from table where condition = '" & e.CommandArgument & "'"
Dbcmd.ExecuteNonQuery()
Dbconn.Close()
Dbconn.Dispose()
End If
If you don't want to use the 'default'/already defined parameters, you can create your own events.

Resources