How to tell which row in datagrid has been clicked.

  • Thread starter Thread starter Terry Olsen
  • Start date Start date
T

Terry Olsen

I have a DataGrid with a Template Column. In the ItemTemplate I have an
ImageButton. I want to have the user select a row by clicking on the
ImageButton.

When the user clicks an ImageButton, how can I tell which row he clicked
on, and then change the image for the ImageButton in that row, and make
sure all the images in the other rows are default?

I have two Images, one of a button in the "Up" position, and another of
the same button in the "Down" position. Sorta like the old Borland
Controls.

Then, when the user clicks the "Submit" button, I need to know which row
of the datagrid was ultimately selected.

Thanks!
 
Hi Terry,

e.Item.ItemIndex in ItemCommand Event is row index of the datagrid.

HTH

Elton Wang
 
Yes, but when I click the ImageButton, it posts back but doesn't seem to
fire the Datagrid.IndexChanged event.
 
The best is to do everything on client side.

In ItemDataBound event setup client side "onclick" event for every data item
like this:

private void dgSelection_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// provide client-side selection a datagrid row upon clicking
any place on the row.
ListItemType itemType = e.Item.ItemType;
if ((itemType == ListItemType.Pager) ||
(itemType == ListItemType.Header) ||
(itemType == ListItemType.Footer))
{
return;
}
e.Item.Attributes["onclick"] = "onRowClick(this)";
}

Javascript onRowClick function gets a clicked row as a parameter. It can
access individual cells and their content via cells property. It can get
down to the image and change its url. It can also remember the last selected
row and return it's image to default. Also it can store the selected row id
in a hidden input control to be available on server side after clicking
"Submit".

Eliyahu
 
Back
Top