473,701 Members | 2,718 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to determine which cell was clicked in as ASP.NET DataGrid

Hi,



I created an ASP.NET Datagrid where a single row can be selected by clicking anywhere on the row (according to http://msdn.microsoft.com/library/de...verControl.asp, Selecting Rows by Clicking Anywhere).



Private Sub DataGrid1_ItemD ataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.W ebControls.Data GridItemEventAr gs) _
Handles DataGrid1.ItemD ataBound
Dim itemType As ListItemType = e.Item.ItemType
If ((itemType = ListItemType.Pa ger) Or _
(itemType = ListItemType.He ader) Or _
(itemType = ListItemType.Fo oter)) Then
Return
Else
Dim button As LinkButton = _
CType(e.Item.Ce lls(0).Controls (0), LinkButton)
e.Item.Attribut es("onclick") = _
Page.GetPostBac kClientHyperlin k(button, "")
End If
End Sub

Additionally I want to be able to know which cell was clicked. Does anybody know how this can be done?



Thank you a lot in advance!



Daniel
Nov 18 '05 #1
2 3177
"Daniel Walzenbach" <da************ **********@freu denberg.de> wrote in message news:e5******** ******@TK2MSFTN GP10.phx.gbl...
Hi,



I created an ASP.NET Datagrid where a single row can be selected by clicking anywhere on the row (according to http://msdn.microsoft.com/library/de...verControl.asp, Selecting Rows by Clicking Anywhere).



Private Sub DataGrid1_ItemD ataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.W ebControls.Data GridItemEventAr gs) _
Handles DataGrid1.ItemD ataBound
Dim itemType As ListItemType = e.Item.ItemType
If ((itemType = ListItemType.Pa ger) Or _
(itemType = ListItemType.He ader) Or _
(itemType = ListItemType.Fo oter)) Then
Return
Else
Dim button As LinkButton = _
CType(e.Item.Ce lls(0).Controls (0), LinkButton)
e.Item.Attribut es("onclick") = _
Page.GetPostBac kClientHyperlin k(button, "")
End If
End Sub

Additionally I want to be able to know which cell was clicked. Does anybody know how this can be done?



Thank you a lot in advance!


I'm not certain, but I think that if you use something other than "" for the second parameter to GetPostBackClie ntHyperlink, then the parameter will be passed as Request.Form("_ _EVENTARGUMENT" ).
--
John Saunders
johnwsaundersii i at hotmail
Nov 18 '05 #2
Hi Daniel,

From your description, you've made the WebForm DataGrid fire the Select
Command when click anywhere on a datagrid row via the following tech
article:
http://msdn.microsoft.com/library/de...us/dv_vstechar
t/html/vbtchTopQuestio nsAboutASPNETDa taGridServerCon trol.asp

I've read the above article and also generate some tests based on it. Since
the webform DataGrid is different from winform which doesn't provide
buildin means to get the current clicked cell because the Webform datagrid
is actually rendered out to clientside as a <table> ....</table> html
element. And each row of the dataGrid is a <tr> ...</tr>
each cell is a <td>... </td>

And in the article, it make use of the ItemDataBound event and add a
"onclick" clientside event for the DataGridItem Row so that when we click
on anywhere within a DataGrid Row , it'll fire the select command event.
However, the select command doesn't contain any information about which
Cell(Column) in the DataGrid row is clicked, yes?
I've tried John's suggestion on using the second param of the
Page.GetPostBac kClientHyperlin k(button, "") method , but found it won't
work for this issue.

Currently, my solution on this problem is still using the ItemDataBound
event, in addition to add and "onclick" clientside event for each
DataGridItem, we also have to add a "onclick" event functoin for each Cell
of the Item, forexample,
Dim col As Integer
For col = 0 To e.Item.Cells.Co unt - 1
e.Item.Cells(co l).Attributes.A dd("onclick",
"setCurrentColu mn('" & col & "')")
Next

And the "setCurrentColu mn" is a javascript function in the Page which set a
value to a <input type=hidden ..> elemetn in the page. You can see we use
this javascript to assign the current clicked Cell(<td>..</td>)'s columsn
index to the <input type=hidden ..> element. And we need to put the row
information of the currrent click Cell's Row index in the LinkButton's
CommandArgument as below:
Dim button As LinkButton = _
CType(e.Item.Ce lls(0).Controls (0), LinkButton)

Dim row As Integer = e.Item.ItemInde x
button.CommandA rgument = row.ToString()
Then, in the DataGrid's ItemCommand event, we can get the current selected
Cell's row/col info like below:
Private Sub dgMain_ItemComm and(ByVal source As Object, ByVal e As
System.Web.UI.W ebControls.Data GridCommandEven tArgs) Handles
dgMain.ItemComm and
If e.CommandName = "Select" Then
Response.Write( "<br>Row: " + e.CommandArgume nt)
Response.Write( "<br>Col: " + hdCell.Value)

End If

End Sub
To make it clearly, I've pasted my test page's code at the bottom of this
message. Please refer to it if you have anything unclear. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx

=============== =========aspx =============== ===============
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>CellGrid </title>
<meta name="GENERATOR " content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
<script language="javas cript">
function setCurrentColum n(col)
{
document.getEle mentById("hdCel l").value = col;
}
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="100%" align="center">
<tr>
<td></td>
</tr>
<tr>
<td>
<asp:DataGrid id="dgMain" runat="server" AutoGenerateCol umns="False">
<Columns>
<asp:ButtonColu mn Text="Select" HeaderText="Sel ect"
CommandName="Se lect"></asp:ButtonColum n>
<asp:BoundColum n DataField="inde x"
HeaderText="Ind ex"></asp:BoundColumn >
<asp:BoundColum n DataField="name "
HeaderText="Nam e"></asp:BoundColumn >
<asp:BoundColum n DataField="emai l"
HeaderText="Ema il"></asp:BoundColumn >
</Columns>
</asp:DataGrid></td>
</tr>
<tr>
<td><INPUT id="hdCell" type="hidden" name="hdCell" runat="server"
value="0|0"></td>
</tr>
</table>
</form>
</body>
</HTML>
=============== code behind========= =============== ==============
Public Class CellGrid
Inherits System.Web.UI.P age

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnos tics.DebuggerSt epThrough()> Private Sub
InitializeCompo nent()

End Sub
Protected WithEvents dgMain As System.Web.UI.W ebControls.Data Grid
Protected WithEvents hdCell As
System.Web.UI.H tmlControls.Htm lInputHidden

'NOTE: The following placeholder declaration is required by the Web
Form Designer.
'Do not delete or move it.
Private designerPlaceho lderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeCompo nent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
If Not IsPostBack Then
Bind_Data()
End If
End Sub

Private Sub Bind_Data()
Dim tb As New DataTable("MyUs er")
tb.Columns.Add( "index", GetType(Integer ))
tb.Columns.Add( "name", GetType(String) )
tb.Columns.Add( "email", GetType(String) )

Dim row As DataRow
Dim i As Integer
For i = 1 To 10
row = tb.NewRow()
row("index") = i
row("name") = "Name" + i.ToString()
row("email") = "Name" + i.ToString() + "@test.com"

tb.Rows.Add(row )
Next

dgMain.DataSour ce = tb
dgMain.DataBind ()

End Sub

Private Sub dgMain_ItemData Bound(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Data GridItemEventAr gs) Handles
dgMain.ItemData Bound
Dim itemType As ListItemType = e.Item.ItemType
If ((itemType = ListItemType.Pa ger) Or _
(itemType = ListItemType.He ader) Or _
(itemType = ListItemType.Fo oter)) Then
Return
Else
Dim button As LinkButton = _
CType(e.Item.Ce lls(0).Controls (0), LinkButton)

Dim row As Integer = e.Item.ItemInde x
button.CommandA rgument = row.ToString()
e.Item.Attribut es("onclick") = _
Page.GetPostBac kClientHyperlin k(button, "")

Dim col As Integer
For col = 0 To e.Item.Cells.Co unt - 1
e.Item.Cells(co l).Attributes.A dd("onclick",
"setCurrentColu mn('" & col & "')")
Next

End If

End Sub

Private Sub dgMain_Selected IndexChanged(By Val sender As Object, ByVal e
As System.EventArg s) Handles dgMain.Selected IndexChanged

End Sub

Private Sub dgMain_ItemComm and(ByVal source As Object, ByVal e As
System.Web.UI.W ebControls.Data GridCommandEven tArgs) Handles
dgMain.ItemComm and
If e.CommandName = "Select" Then
Response.Write( "<br>Row: " + e.CommandArgume nt)
Response.Write( "<br>Col: " + hdCell.Value)
'Response.Write ("<br>CommandAr gument: " + e.CommandArgume nt)
'Response.Write ("<br>CommandSo urce: " +
e.CommandSource .ToString())
End If

End Sub
End Class

Nov 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7074
by: Charlie | last post by:
Hi: Using the WinForms DataGrid, I would like to have the entire row highlight rather than just the cell that was last clicked. How do you do this? Thanks, Charlie
1
1885
by: orekinbck | last post by:
Hi There I have a datagrid whose main purpose in life is to provide a nice way for users to make a single choice from a list. The grid is read only, single row select and has its data source as an ArrayList. I came up against the issue of selecting a cell and getting the whole row to highlight, and the second issue of unhighlighting any previously selected row. To get around these two issues I have put in a two prong approach:
6
1695
by: EMW | last post by:
How can I detect on which cell the user has clicked on a datagrid webcontrol? rg, Eric
1
1461
by: Tor Inge Rislaa | last post by:
Find what cell is clicked in a datagrid When clicking a cell in the datagrid I can't see that the click event is raised. As I can understand the click event is raised when the column or row header is clicked. Is there an event that can be used to find the current cell when you click it?
21
2377
by: coleenholley | last post by:
I've been trying since last Friday to get an answer on how to get a SPECIFIC row.cell value from a datagrid. I've had plenty of suggestions, but nothing works to get the value from a SPECIFIC Row and cell. Right now I have this code Sub Item_Bound(ByVal sender As Object, ByVal e As DataGridItemEventArgs lbl_test.Text = lbl_test.Text & " " & e.Item.ItemInde Session("wa_tot_gal") = e.Item.Cells(7).Tex Response.Write(Session("wa_tot_gal")...
10
4948
by: JohnR | last post by:
I have a datatable as the datasource to a datagrid. The datagrid has a datagridtablestyle defined. I use the datagridtablestyle to change the order of the columns (so they can be different than the column order of the datatable). I also allow the user to click on a column header to sort the datagrid by that column. I need to identify the row and column in the datatable when the user clicks on a cell in the datagrid. Using the...
0
1296
by: theintrepidfox | last post by:
Dear Group I really need your help on this issue. I've a datagrid which source is a dataview based on a dataset. The columns of the grid are datagridtextbox columns created like the following example: Dim Column1 As New DataGridTextBoxColumn With Column1
2
2085
by: benfly08 | last post by:
Hi, everyone. I got a weird problem for my C# program. In my program, I use a DataGrid to display data. I bind the DataGrid to a DataTable. I made all the cells in DataGrid ReadOnly as True. So I can only Click on the cell but not change them. Now, after I display the data, I clicked on one cell, then I clicked a button which will *virtually* go to the other form.(The reason why I said *virtually* is because I only use one form for...
0
1420
by: =?Utf-8?B?TWljaGFlbCBKLiBWaXNpbnRpbg==?= | last post by:
Hi All, I am implementing the Paint Method override described in the Help (DataGridTextBoxColumn.PaintMethod). I believe that I have implemented the procedure example displayed in the Help verbatim. I receive no errors, and the debugger shows all of the code being executed, but my new color never appears when I click on the cell of the grid. Are there any general things I can look for besides things like making sure my rectangle is...
0
8649
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9232
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8936
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7827
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6573
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4411
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4665
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3104
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2036
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.