How to call 2 events inside the datagrid

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have fetched a query in to the datagrids. Now I have added a new column to
the existing table (to the datagrid.)
In the new column I have placed 2 buttons. So when I click the first button
it performs some set of instruction. I actually made use of this procedure
DataGrid1_ItemCommand.

Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs)
End Sub

Now my question is how will able to use the other one? coz when I double
click the second button, it is nowhere land me in to a new procedure..

Let me know you thoughts..
 
hi velu,
great, i think we are getting somewhere. this is a good opportunity to
explain why you are getting a 'dud' postback, i.e. when you click the button
but your button event handler doesn't fire.

with the code-behind model, we tend to think that when we click the button,
it magically calls our button event handler. and although this is a nice
way to think about it, it is too simplistic and it skips some very important
steps.

remember that when you click the button, you are really submitting a form
(at the html level). the action of this form is set to the address of the
page itself. the page is requested (again), with the form 'post'
information. this contains what is called the 'event target', i.e. the
control that caused the postback, in your case, it is the second button.

it is very important to remember that the page before the postback, and the
page after the postback, are separate pages, that are both loaded from
scratch, both going through the process of Page_Load etc. the only
difference is the second page has some form post information, and of course
the viewstate which maintains the state of the controls. any controls that
were created programatically the first time, must also be re-created the
second time (especially if they have events).

in your scenario, as i understand it, you create some controls
programatically, like the panel and the button, that are set to
visible=false. after the post back happens, you still create these controls
in the datagrid column, and they are still set to visible=false. to my
understanding, as far as the server-side is concerned, the button is not
capable of handling events, hence the dud postback. the 'event target' that
was submitted with the form, does not refer to anything now because the
control doesn't exist, so the event gets missed. the fact that the buttom
may remain on screen is due to the state preservation provided by viewstate.

if you post your code i should be able to tell you how to work around this,
and hopefully it will be a lesson in the postback lifecycle as well.
please include the datagrid aspx source, as well as the Page_Load,
DataGrid_ItemCommand, and especially the code that adds the panel and button
to the datagrid column.

tim
 
HI Tim Mackey,
I must say that for educative than information to make sense.

Ok, here I am sharing the full code….

The ASPX file

<form id="Form1" method="post" runat="server">
<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 8px; POSITION:
absolute; TOP: 8px" runat="server" AutoGenerateColumns="False" Width="500px">
<AlternatingItemStyle Font-Size="Smaller"
Font-Names="Verdana,Arial,Helvetica,sans-serif"
BackColor="#E5E5E5"></AlternatingItemStyle>
<ItemStyle Font-Size="Smaller"
Font-Names="Verdana,Arial,Helvetica,sans-serif"
BackColor="#F2F2F2"></ItemStyle>
<HeaderStyle Font-Size="Smaller"
Font-Names="Verdana,Arial,Helvetica,sans-serif" Font-Bold="True"
HorizontalAlign="Center" ForeColor="#3D3DB6"
BackColor="#E8EBFD"></HeaderStyle>
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="documentURL"
DataTextField="documentLabel" HeaderText="Developer
Guides"></asp:HyperLinkColumn>
<asp:BoundColumn DataField="documentFormat" ReadOnly="True"
HeaderText="Format"></asp:BoundColumn>
<asp:BoundColumn DataField="documentDate" ReadOnly="True"
HeaderText="Date"></asp:BoundColumn>
<asp:BoundColumn Visible="False" DataField="avgRating" ReadOnly="True"
HeaderText="Number_Rating"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Rating">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
<ItemTemplate>
<asp:label id="lblStarRating" runat="server"></asp:label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="RatingCount" ReadOnly="True" HeaderText="Rating
Count">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="Rate It">
<ItemTemplate>
<P>
<asp:LinkButton id="LinkButton1"
runat="server">LinkButton</asp:LinkButton></P>
<asp:Panel id="Panel1" runat="server" Height="212px" Visible="False">
<P>Rate it form.
</P>
<P>
<asp:Label id="Label1" runat="server">You have already rated
this..!</asp:Label></P>
<P>
<asp:RadioButtonList id="RadioButtonList1" runat="server">
<asp:ListItem Value="1">*</asp:ListItem>
<asp:ListItem Value="2">**</asp:ListItem>
<asp:ListItem Value="3">***</asp:ListItem>
<asp:ListItem Value="4">****</asp:ListItem>
<asp:ListItem Value="5">*****</asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox id=TextBox2 runat="server" Text='<%#
DataBinder.Eval(Container,"DataItem.DocumentID") %>'>
</asp:TextBox></P>
<P>
<asp:TextBox id="TextBox1" runat="server" Width="208px"
Height="145px"></asp:TextBox></P>
<P>
<asp:Button id="Button1" runat="server" Text="Rate it"
CommandName="Rate_it"></asp:Button></P>
</asp:Panel>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="documentID" HeaderText="document
ID"></asp:BoundColumn>
</Columns>
</asp:datagrid>
</form>


The VB Coding part


Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.Panel
Imports System.Data.DataColumn

Public Class WebForm1
Inherits System.Web.UI.Page
'Globle Variables
Dim conPubs As SqlConnection
Dim DocumentID As Integer

#Region " Web Form Designer Generated Code "


#Region "On Page Load"

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim cmdSelect As SqlCommand
conPubs = New
SqlConnection("server=BGLAMDJVELU;Database=Pubs;Integrated security=sspi")
cmdSelect = New SqlCommand("select D.documentID, D.documentType,
D.documentLabel, D.documentURL, D.documentFormat, D.documentDate,
COALESCE(AVG(rating),0) AS avgRating, (COUNT(rating)) AS RatingCount from
tbl_documents as D left outer join tbl_Rating as R on R.documentID =
D.documentID group by D.documentID, D.documentLabel, D.documentType,
D.documentURL, D.documentFormat, D.documentDate", conPubs)

conPubs.Open()
DataGrid1.DataSource = cmdSelect.ExecuteReader()
DataGrid1.DataBind()
conPubs.Close()
End Sub

#End Region

#Region "Converting Date into Star"
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataGridItemEventArgs) Handles
DataGrid1.ItemDataBound
If ((e.Item.ItemType <> ListItemType.Header) And (e.Item.ItemType <>
ListItemType.Footer)) Then
Dim MyLabel As Label
MyLabel = CType(e.Item.FindControl("lblStarRating"), Label)
Dim i As Int32
i = Convert.ToInt32(e.Item.Cells(3).Text)
DocumentID = Convert.ToInt32(e.Item.Cells(7).Text)
Dim j As Int32 = 0
MyLabel.Text = ""
If i <= 0 Then
MyLabel.Text = "Be the first to rate it!!"
End If
For j = 1 To i
'MyLabel.Text += "*" 'rating in "*"
MyLabel.Text += "<IMG id='IMG1' src='stars.gif' >"
Next

End If

End Sub
#End Region

Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs) Handles
DataGrid1.ItemCommand

' users IP address.
Dim UserIP As String
UserIP = (Request.UserHostAddress)
' Get the IP address from database
'Open the connection, and execute the query...
Dim intCount As Integer
Dim cmdvrfy As SqlCommand
cmdvrfy = New SqlCommand("Select * FROM tbl_rating Where DocumentID
=" & DocumentID & "AND ip ='" & UserIP & "';", conPubs)
conPubs.Open()
cmdvrfy.Connection = conPubs
cmdvrfy.CommandType = CommandType.Text
intCount = cmdvrfy.ExecuteScalar()
conPubs.Close()
If intCount = "0" Then '127.0.0.1
'Opens the Panel for the user !
Dim MyPanel As Panel
MyPanel = (e.Item.FindControl("Panel1"))
MyPanel.Visible = True
Else
MsgBox("You have already reated this !!!!")
End If


End Sub

End Class

Thx The main purpose is to create a 5 star rating system inside a table that
displays the article name….

Let know your thoughts.

Hey you have nice blog…
Thx
JK
 
hi velu,
the problem is simpler than i was anticipating. i thought you were
dynamically creating the panel + button in your code.

the only thing you were missing is handling each datagrid command
individually. in the aspx, i added a commandname "Open_panel" to the first
linkbutton:
<asp:LinkButton id="LinkButton1" runat="server"
CommandName="Open_panel">LinkButton</asp:LinkButton>

then in the DataGrid1_ItemCommand, i added a "select case" statement to
determine which command was invoked (rate_it or open_panel), and act
accordingly.

take a look at the following code

Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs) Handles
DataGrid1.ItemCommand
Select Case e.CommandName
Case "Open_panel"
e.Item.FindControl("Panel1").Visible = True
Case "Rate_it"
Dim txt As TextBox, rdb As RadioButtonList
txt = e.Item.FindControl("TextBox1")
rdb = e.Item.FindControl("RadioButtonList1")
Response.Write("RadioButton: " & rdb.SelectedValue & ",
Text: " & txt.Text)
'do some database stuff here, whatever...
End Select
End Sub

this should get it working for you. you can ignore that stuff i wrote about
post backs, it wasn't very relevant!

hope this helps
tim
 
HI Tim Mackey,

Sorry for the delay. I was on vacation and did not have access to the
Internet and dot.net ;-) as well.

Yup the Solution works. So I am I can make use the command name in a good
sense. But I could not insert a new record. Any way I have added the code for
you. Let me know you comments..

Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs) Handles
DataGrid1.ItemCommand


Select Case e.CommandName

Case "Open_panel"
' users IP address.
Dim UserIP As String
UserIP = (Request.UserHostAddress)
' Get the IP address from database
'Open the connection, and execute the query...
Dim intCount As Integer
Dim cmdvrfy As SqlCommand
cmdvrfy = New SqlCommand("Select * FROM tbl_rating Where
DocumentID =" & DocumentID & "AND ip ='" & UserIP & "';", conPubs)
conPubs.Open()
cmdvrfy.Connection = conPubs
cmdvrfy.CommandType = CommandType.Text
intCount = cmdvrfy.ExecuteScalar()
conPubs.Close()
If intCount = "0" Then '127.0.0.1
'Opens the Panel for the user !
e.Item.FindControl("Panel1").Visible = True
Else
e.Item.FindControl("Label1").Visible = True
End If

Case "Rate_it"
Dim rate As Integer
Dim RadioButtonList1 As RadioButtonList
rate = RadioButtonList1.SelectedValue()

Dim UserIP As String
UserIP = (Request.UserHostAddress)

Dim comments As String
Dim TextBox1 As TextBox
comments = TextBox1.Text

Dim DocumentID As Integer
Dim TextBox2 As TextBox
DocumentID = TextBox2.Text

Dim conPubs As SqlConnection
Dim cmdSelect As SqlCommand
conPubs = New
SqlConnection("server=BGLAMDJVELU;Database=Pubs;Integrated security=sspi")
cmdSelect = New SqlCommand("INSERT INTO tbl_rating (rating,
ip, documentID, usercomment) VALUES (" & rate & " ,'" & UserIP & "'," &
DocumentID & ",'" & comments & "');", conPubs)
conPubs.Open()
cmdSelect.ExecuteReader()
conPubs.Close()

End Select

Thx
JK
 
hi velu,
is it that the 'rate-it' command doesn't appear to work?
i noticed you don't call BindGrid() or whatever function you use to
re-display the datagrid. after you change the database, you will need to
re-bind the datagrid if you want the change to be visible.

hope this helps
tim
 
HI tim, I am glad you are back.

I did try thru Button for the “rate_it†command name. but it dent work. But
I replaced it with link button. So now the “rate_it†fine for me

Now my exact problem is. I couldn’t get the value for rate, comments,
DocumentID
I know there is something wrong in the code below. Let me know your thoughts.
May be after that I will try binding stuff..

Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs) Handles
DataGrid1.ItemCommand

Select Case e.CommandName

Case "Open_panel"
‘ some code here


Case "rate_it"


Dim rate As String
Dim RBL As New RadioButtonList
RBL = CType(e.Item.FindControl("RadioButtonList1"),
RadioButtonList)
rate = Request.Form("RadioButtonList1")

Dim UserIP As String
UserIP = CStr(Request.UserHostAddress)

Dim comments As String
Dim TB As TextBox
TB = CType(e.Item.FindControl("TextBox1"), TextBox)
comments = TB.Text

Dim DocumentID As Integer
Dim TB2 As TextBox
TB = CType(e.Item.FindControl("TextBox2"), TextBox)
DocumentID = TB2.Text

Dim conPubs As SqlConnection
Dim cmdSelect As SqlCommand
conPubs = New
SqlConnection("server=BGLAMDJVELU;Database=Pubs;Integrated security=sspi")
cmdSelect = New SqlCommand("INSERT INTO tbl_rating (rating,
ip, documentID, usercomment) VALUES (" & rate & " ,'" & UserIP & "'," &
DocumentID & ",'" & comments & "');", conPubs)
conPubs.Open()
cmdSelect.ExecuteReader()
conPubs.Close()

End Select
 
hi velu,
i'm not sure why you are accessing the rate through Request.Form, when you
already have the RBL variable. i would use RBL.SelectedValue for the rate.

the code you have to access the textbox values appears to be correct. can
you find out exactly what exception you are getting, and at what line it is
failing.

tim
 
Hi Tim, sorry for the delay, Was not in town anyway..b2b

I did try changing the code from form request to like this…

Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs) Handles
DataGrid1.ItemCommand

Select Case e.CommandName

Case "Open_panel"
‘some code


Case "rate_it"

Dim rate As String

Dim DocumentID as integer
DocumentID = Convert.ToInt32(e.Item.Cells(7).Text)

Dim RBL As New RadioButtonList
RBL = CType(e.Item.FindControl("RadioButtonList1"),
RadioButtonList)
rate = Request.Form("RadioButtonList1")

Dim UserIP As String
UserIP = CStr(Request.UserHostAddress)

Dim comments As String
Dim TB As TextBox
TB = CType(e.Item.FindControl("TextBox1"), TextBox)
comments = TB.Text

Dim DocumentID As Integer
Dim TB2 As TextBox
TB = CType(e.Item.FindControl("TextBox2"), TextBox)
DocumentID = TB2.Text

Dim conPubs As SqlConnection
Dim cmdSelect As SqlCommand
conPubs = New
SqlConnection("server=BGLAMDJVELU;Database=Pubs;Integrated security=sspi")
cmdSelect = New SqlCommand("INSERT INTO tbl_rating (rating,
ip, documentID, usercomment) VALUES (" & rate & " ,'" & UserIP & "'," &
DocumentID & ",'" & comments & "');", conPubs)
conPubs.Open()
cmdSelect.ExecuteReader()
conPubs.Close()
End Select


But nothing is thrown as exception. When I click the submit button. It
closes. But it doesn’t store any value in the various fields I declared
above. So I am not able to insert any value in to the table…..any thoughts ?

thx
JK
 
hi velu,
you're still using the Request object unnecessarily:
rate = Request.Form("RadioButtonList1")

this should be something like rate = RBL.SelectedValue

the best thing to do at this stage is do some debugging yourself and find
out what code is getting run and what isn't. if you can't debug, use
Tracing. see the .net reference for more info on debugging and tracing if
you need it.

sorry i can't be of more help.
tim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top