How to call 2 events inside the datagrid

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..
 
T

Tim_Mac

hi velu,
firstly i should point out that double-clicking on a web page is usually not
what you want. it just performs the same request twice, and you miss the
response from the first one because by clicking it a second time, the
browser aborted that request and initiated a second one. the first request
may or may not be executed fully.

do you want the second button to perform a different command when it is
clicked? if so you should set the CommandName on the button (in the aspx)
to a different command. e.g. the Edit button should have CommandName=Edit.
the Delete button should have CommandName=Delete.
then the DataGrid1_ItemCommand will be able to determine which button was
clicked, and act appropriately.

if you want the same button to do two tasks, you could just combine those
tasks in the DataGrid1_ItemCommand method. or if you specifically want the
DataGrid1_ItemCommand method to be invoked twice, with 2 different
commandNames, based on one button click... you could call the function a
second time, creating new event args, with the new command name, as shown
below.

here is some code, although it doesn't make much sense to invoke the
ItemCommand twice, you should really just separate the commands into
functions, and call the function instead of trying to simulate a new
ItemCommand on the datagrid:

private void DataGrid1_ItemCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
switch(e.CommandName)
{
case "Delete":
// insert delete code here
// ...

// now invoke the 'Command2' command, by calling this method again, with
new event args
this.DataGrid1_ItemCommand(source, new DataGridCommandEventArgs(e.Item,
e.CommandSource, new CommandEventArgs("Command2","")));
break;


case "Edit":
break;


case "Command2":
// execute command2...
break;
}
}

maybe you could clarify exactly what you want to do, and we can take it from
there.

thanks

tim
 
G

Guest

HI Tim_Mac,

Actually I have 2 buttons inside a Column of a data grid. The Column has a
Panel and its view is disabled. A button is placed out side the panel and a
second button is placed inside the panel.

When the users click the first button the panel is enabled. Then when the
user click the second button (the button inside the panel) perform some
instruction like inserting a insert rec in to the database.. I think I made
it clear…let me know if you still need more info

Thx
JK
 
T

Tim_Mac

hi velu,
ok, i see what you are doing now.
i'm assuming that the first button works properly, and enables the panel
containing the second button, but the second button does nothing when you
click on it.

can you check that you have a CommandName set for the second button?
also, if you are creating the new column programmatically, you probably know
that it needs to be created for every post back. i'm guessing you are
already doing this, and since the second button and panel are disabled, the
button command won't happen. you may need to add a special case in your
code to create the column, to create the panel disabled the first time, and
then create it enabled after the first button has been clicked. you could
use some variable added to viewstate to accomplish this. e.g.
ViewState["EnableSecondPanel"] = "true";

let me know if i have answered your question.

thanks
tim
 
G

Guest

Hi Tim_Mac,

you said "ok, i see what you are doing now. i'm assuming that the first
button works properly, and enables the panel containing the second button,
but the second button does nothing when you click on it." - Bulls eye, you
are rit !

Let me explain a little bit more in detail.

[Remember all the lines below are place inside a single column of the
datagrid along with the existing table that fetches a query.]

By default the Panel is set to visible=false. And button 2 is inside the
panel which is also not visible. so when I click the button 1 (which is out
side the panel) the visiable is set to true. I have used the following
procedure to achieve this. There are as follows.

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

Dim MyPanel As Panel
MyPanel = (e.Item.FindControl("Panel1"))
MyPanel.Visible = True

End Sub

Now the panel is visible along with some small text boxes and the button 2.
Now what I am looking for is listed below:

1--- When I click the button 2, it must insert a record into the database.
(I exactly don’t know where to create procedure…)
2---after inserting the record into database, I want to hide panel along
with the button2. To make sure that the user doesn’t use this again. (the
rating kinda stuff)
3---last things is, after inserting the record from an exact row, the row
itself must get updated.

If you need more details, I also show all the code I have used…

Thx
jk


Tim_Mac said:
hi velu,
ok, i see what you are doing now.
i'm assuming that the first button works properly, and enables the panel
containing the second button, but the second button does nothing when you
click on it.

can you check that you have a CommandName set for the second button?
also, if you are creating the new column programmatically, you probably know
that it needs to be created for every post back. i'm guessing you are
already doing this, and since the second button and panel are disabled, the
button command won't happen. you may need to add a special case in your
code to create the column, to create the panel disabled the first time, and
then create it enabled after the first button has been clicked. you could
use some variable added to viewstate to accomplish this. e.g.
ViewState["EnableSecondPanel"] = "true";

let me know if i have answered your question.

thanks
tim

--------------------------
blog: http://tim.mackey.ie


velu said:
HI Tim_Mac,

Actually I have 2 buttons inside a Column of a data grid. The Column has a
Panel and its view is disabled. A button is placed out side the panel and
a
second button is placed inside the panel.

When the users click the first button the panel is enabled. Then when the
user click the second button (the button inside the panel) perform some
instruction like inserting a insert rec in to the database.. I think I
made
it clear.let me know if you still need more info

Thx
JK
 
T

Tim_Mac

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
 
G

Guest

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
 
T

Tim_Mac

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
 
G

Guest

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
 
T

Tim_Mac

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
 
G

Guest

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
 
T

Tim_Mac

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
 
G

Guest

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
 

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

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,690
Members
48,796
Latest member
Greg L.

Latest Threads

Top