Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I get the Index of the cell clicked?

Status
Not open for further replies.

dpdoug

Programmer
Nov 27, 2002
455
US
I know that e.Item.Cells(0).Text will return the contents of the first cell in the row of a DataGrid, but my question is what if I don't know what cell they clicked on?

If I could get the index of the cell the user clicked on, I could do this:

Code:
Dim intCellIndexClicked As Integer

intCellIndexClicked = [get me the cell index]

Dim strContentsOfClickedCell As String = _
   e.Item.Cells(intCellIndexClicked).Text

How do I get the Index of the cell clicked?
 
With a web datagrid? I don't think you can...the datagrid commands (select, edit, delete, etc.) provide the means of getting the item (row), but not necessarily the actual cell clicked.

I suppose there's a way, but it probably requires extending the datagrid control or writing alot of javascript. You might be better off getting a 3rd party grid like Infragistics, which will allow you to track which cell was clicked.

D
 
You can assign it. Use the DataKeys collection. Assign the DataKeyField property of your grid to your primary key field:
DataGrid1.DataKeyField = "myID";
Then retrieve it via in the DataGrid1_ItemCommand:
int myID = (int)DataGrid1.DataKeys[e.Item.ItemIndex];
or VB version
Dim myID as Integer
myID = DataGrid1.DataKeys(e.Item.ItemIndex)
Works the same with DataList.
 
That still only provides the index of the item (or row), but it won't return the actual cell index clicked within the row.

D
 
Sorry, I misread the post. Having re-read, I agree with you.
 
There is not an onclick event for a datagrid. You would need to do something like this:

YOUR ASPX PAGE:
<asp:DataGrid Runat="server" ID="DataGrid1">
<Columns>
<asp:TemplateColumn >
<ItemTemplate>
<asp:imagebutton runat="server" OnClick="CellClicked" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"MyIndex")%>' ID="imgMyImage" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>



YOUR CODE BEHIND PAGE:
Public Sub MyImage_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim MyIndex As Integer = CType(sender, ImageButton).CommandArgument
'You can determine if the index=21 and the grid has 10 columns then it is row 3 column 1
End Sub

NOTES:
The MyIndex column above could be one that you add to an existing datatable. Iterate thru it first and increment by one.
Not sure why if you are using a datatable why you would not just pass back the ID key of your record rather needing to know what column and cell it is.






 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top