Link to home
Start Free TrialLog in
Avatar of dotnet22
dotnet22

asked on

select a row from a datagrid

How can I select a row from a datagrid? Right now when the mouse is over a row, nothing happens if a row is double clicked? Is there an event that catched a click on a row?
Avatar of Magic55
Magic55

Here is MS's:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwebteam/html/webteam11062001.asp

However, just add a select colum but make it hidden.  Then using the ItemCreated event, add DHTML to simulate the button click:

        Private Sub dgInv_ItemCreated(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgInv.ItemCreated
            ' Everytime a datagrid item is created, add DHTML to it
            If e.Item.ItemType = ListItemType.Item Or _
               e.Item.ItemType = ListItemType.AlternatingItem Or _
               e.Item.ItemType = ListItemType.SelectedItem Then

                e.Item.Attributes.Add("onclick", "javascript:__doPostBack('ucProductLookup$dgInv$_ctl" & (e.Item.ItemIndex + 2).ToString & "$_ctl0','')")

            End If
        End Sub
The easiest way I found to enter the exact "javascript function" is to first leave the select column visible, then view the page to see what the link is.  Then enter it like shown above...
Please see my post here:
https://www.experts-exchange.com/questions/21146979/datagrid-highlighting.html

This is exactly what your looking for, see it in action here:
http://aj.testing.chilitech.net/displaygroup.aspx?gid=149

I provided all the source code for you

Regards,

Aeros
You will need to use a datalist for this here is a wonderful example:
<%@ Page language="vb"  Inherits="DOTNETShoppingCart.PagingDataList" CodeBehind="PagingDataList.aspx.vb" AutoEventWireup="false" %>
<HTML>
     <HEAD>
          <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
          <style>
.GridHeader TD { PADDING-RIGHT: 20px; FONT-WEIGHT: bold; BORDER-BOTTOM: black 2px solid; WHITE-SPACE: nowrap }
.GridItem TD { PADDING-RIGHT: 5px; PADDING-LEFT: 5px; FONT-WEIGHT: normal; PADDING-BOTTOM: 5px; CURSOR: hand; PADDING-TOP: 5px; BORDER-BOTTOM: white 1px solid; FONT-FAMILY: Courier New; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #ffffff; asp: Literal id="ItemLetterSpacing" runat="server"></asp:Literal> --> }
.GridItemAlternate TD { PADDING-RIGHT: 5px; PADDING-LEFT: 5px; FONT-WEIGHT: normal; PADDING-BOTTOM: 5px; CURSOR: hand; PADDING-TOP: 5px; BORDER-BOTTOM: white 1px solid; FONT-FAMILY: Courier New; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #f3f3f3; asp: Literal id="AltItemLetterSpacing" runat="server"></asp:Literal> --> }
.GridItemOver TD { PADDING-RIGHT: 5px; PADDING-LEFT: 5px; FONT-WEIGHT: bold; PADDING-BOTTOM: 5px; CURSOR: hand; PADDING-TOP: 5px; FONT-FAMILY: Courier New; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #fffdce }
.GridItemInactive TD { PADDING-RIGHT: 5px; PADDING-LEFT: 5px; FONT-WEIGHT: normal; PADDING-BOTTOM: 5px; CURSOR: hand; PADDING-TOP: 5px; BORDER-BOTTOM: white 1px solid; FONT-FAMILY: Courier New; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #d5dbe1; asp: Literal id="InactiveItemLetterSpacing" runat="server"></asp:Literal> --> }
          </style>
          <script language="javascript">
<!--
function openLocation(newlocation) {
     if (newlocation.length != 0)
          window.location = newlocation;
     else
          return;
}
//-->
          </script>
     </HEAD>
     <body>
          <form runat="server">
               <h3>
                    <H3><asp:datalist id="dtlProducts" runat="server" Width="738px" RepeatColumns="1" DataKeyField="ProductID">
                              <HeaderTemplate>
                                   <table width="100%" cellspacing="0" cellpadding="0">
                                        <tr class="Gridheader">
                                             <th align="left" width="15%">
                                                  Image</th>
                                             <th align="left" width="25%">
                                                  Product Name</th>
                                             <th align="left" width="45%">
                                                  Description</th>
                                             <th align="left" width="15%">
                                                  Price</th>
                                        </tr>
                              </HeaderTemplate>
                              <ItemTemplate>
                                   <tr id="ItemRow" runat="server" class="GridItem" onmouseover="this.className='GridItemOver';"
                                        onmouseout="this.className='GridItem';" onclick='<%# "openLocation(""ProductDetail.aspx?ProductID=" & DataBinder.Eval(Container.DataItem, "ProductID") & """);" %>'>
                                        <td><img src='<%# DataBinder.Eval(Container.DataItem, "ImageSrc", "Pictures/Products/Thumbnails/{0}")%>'></td>
                                        <td><%# DataBinder.Eval(Container.DataItem, "Name") %></td>
                                        <td><%# DataBinder.Eval(Container.DataItem, "Description") %></td>
                                        <td><%# DataBinder.Eval(Container.DataItem, "Price") %></td>
                                   </tr>
                              </ItemTemplate>
                         </asp:datalist></H3>
               </h3>
               <table width="100%">
                    <tr>
                         <td align="left" width="42%"><asp:label id="lblCounts" Runat="server" CssClass="plaintable"></asp:label></td>
                         <TD vAlign="bottom" width="4%"><A id="First" href="pagingdatalist.aspx#BookMark" runat="server" OnServerClick="ShowFirstPage"><IMG src="images/firstpage.gif" border="0"></A>
                         </TD>
                         <TD vAlign="bottom" width="4%"><A id="Previous" href="pagingdatalist.aspx#BookMark" runat="server" OnServerClick="ShowPreviousPage"><IMG src="images/prevpage.gif" border="0"></A>
                         </TD>
                         <TD vAlign="bottom" width="4%"><A id="Next" href="pagingdatalist.aspx#BookMark" runat="server" OnServerClick="ShowNextPage"><IMG src="images/nextpage.gif" border="0"></A>
                         </TD>
                         <TD vAlign="bottom" width="4%"><A id="Last" href="pagingdatalist.aspx#BookMark" runat="server" OnServerClick="ShowLastPage"><IMG src="images/lastpage.gif" border="0"></A>
                         </TD>
                         <TD width="42%">&nbsp;</TD>
                    </tr>
               </table>
               <asp:label id="lblRecordCount" Runat="server" Visible="False"></asp:label><asp:label id="lblCurrentIndex" Runat="server" Visible="False" Text="0"></asp:label><asp:label id="lblPageSize" Runat="server" Visible="False" Text="10"></asp:label>
               <H3>&nbsp;</H3>
          </form>
     </body>
</HTML>

Imports System.Data
Imports System.Data.OleDb
Imports System.Configuration

Public Class PagingDataList : Inherits System.Web.UI.Page

    Protected WithEvents First As System.Web.UI.HtmlControls.HtmlAnchor
    Protected WithEvents Previous As System.Web.UI.HtmlControls.HtmlAnchor
    Protected WithEvents dtlProducts As System.Web.UI.WebControls.DataList
    Protected WithEvents lblCounts As System.Web.UI.WebControls.Label
    Protected WithEvents lblRecordCount As System.Web.UI.WebControls.Label
    Protected WithEvents lblCurrentIndex As System.Web.UI.WebControls.Label
    Protected WithEvents lblPageSize As System.Web.UI.WebControls.Label
    Protected WithEvents Last As System.Web.UI.HtmlControls.HtmlAnchor

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page.IsPostBack() Then
            BindTheData()
        End If
    End Sub

    Private Sub BindTheData()
        Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim DataAdapter As New OleDb.OleDbDataAdapter("SELECT * FROM Products", cnn)
        Dim DataSet As New DataSet
        Dim PageSize As Integer = 10
        cnn.Open()
        If Not Page.IsPostBack() Then
            DataAdapter.Fill(DataSet)
            lblRecordCount.Text = CStr(DataSet.Tables(0).Rows.Count)
            DataSet = Nothing
            DataSet = New DataSet
        End If
        DataAdapter.Fill(DataSet, CInt(lblCurrentIndex.Text), CInt(lblPageSize.Text), "Products")
        dtlProducts.DataSource = DataSet.Tables("Products").DefaultView
        dtlProducts.DataBind()
        cnn.Close()
        ShowCounts()
        cnn.Dispose()
        DataAdapter.Dispose()
    End Sub

    Public Sub ShowFirstPage(ByVal s As System.Object, ByVal e As System.EventArgs)
        lblCurrentIndex.Text = "0"
        BindTheData()
    End Sub

    Public Sub ShowPreviousPage(ByVal s As System.Object, ByVal e As System.EventArgs)
        lblCurrentIndex.Text = CStr(CInt(lblCurrentIndex.Text) - CInt(lblPageSize.Text))
        If CInt(lblCurrentIndex.Text) < 0 Then
            lblCurrentIndex.Text = "0"
        End If
        BindTheData()
    End Sub

    Public Sub ShowNextPage(ByVal s As System.Object, ByVal e As System.EventArgs)
        If CInt(CInt(lblCurrentIndex.Text) + CInt(lblPageSize.Text)) < CInt(lblRecordCount.Text) Then
            lblCurrentIndex.Text = CStr(CInt(lblCurrentIndex.Text) + CInt(lblPageSize.Text))
        End If
        BindTheData()
    End Sub

    Public Sub ShowLastPage(ByVal s As System.Object, ByVal e As System.EventArgs)
        Dim intMod As Integer
        intMod = CInt(lblRecordCount.Text) Mod CInt(lblPageSize.Text)
        If intMod > 0 Then
            lblCurrentIndex.Text = CStr(CInt(lblRecordCount.Text) - intMod)
        Else
            lblCurrentIndex.Text = CStr(CInt(lblRecordCount.Text) - CInt(lblPageSize.Text))
        End If
        BindTheData()
    End Sub

    Private Sub ShowCounts()
        lblCounts.Text = "|Total Rows: <b>" & lblRecordCount.Text
        lblCounts.Text += "</b> | Page:<b> "
        lblCounts.Text += CStr(CInt(CInt(lblCurrentIndex.Text) / CInt(lblPageSize.Text) + 1))
        lblCounts.Text += "</b> of <b>"
        If (CInt(lblRecordCount.Text) Mod CInt(lblPageSize.Text)) > 0 Then
            lblCounts.Text += CStr(CInt(CInt(lblRecordCount.Text) / CInt(lblPageSize.Text) + 1))
        Else
            lblCounts.Text += CStr(CInt(lblRecordCount.Text) / CInt(lblPageSize.Text))
        End If
        lblCounts.Text += "</b> |"
    End Sub
    Private Sub InitializeComponent()

    End Sub
   
    Private Sub dtlProducts_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dtlProducts.ItemDataBound
        Dim TR As HtmlTableRow
        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
            TR = CType(e.Item.FindControl("ItemRow"), Web.UI.HtmlControls.HtmlTableRow)
            If e.Item.ItemType = ListItemType.AlternatingItem Then
                TR.Attributes("onmouseout") = "this.className='GridItemAlternate';"
                TR.Attributes("class") = "GridItemAlternate"
            End If
            If CStr(DataBinder.Eval(e.Item.DataItem, "ProductID")) = "0" Then
                TR.Attributes("class") = "GridItemInactive"
                TR.Attributes("onmouseout") = "this.className='GridItemInactive';"
            End If
        End If
    End Sub

    Private Sub dtlProducts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtlProducts.SelectedIndexChanged

    End Sub
End Class

Regards,

Aeros
ASKER CERTIFIED SOLUTION
Avatar of hismightiness
hismightiness

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
will that do it for anywhere in the row?
Yes, because the ItemCreated handler handles each "item" (cell) in the row.  You can even use this to exclude cells in the row if they are button columns, etc.
Just remember to uncheck the "visible" checkbox for the Select Button column.  That adds the functionality of a Clickable Datagrid and allows you to customize it easily with a few lines of code (to suit your needs per datagrid)...
Add a SelectButton into datagrid. (It can be a LinkButton or a PushButton)
when it is clicked Datagrid_SelectedIndexChanged() event is being raised.
Looks cooler with Javascript and no button;)
Yeah, it is also A LOT more user friendly to click anywhere in the row versus a single column button.  This is something that should've been built-in from the beginning as a default (with the option of using a button).
I agree completely.
Programmers who are always in a hurry to finish something like me, dont have time to implement it.
Working fast is better, not making best.
everything he needs is in this post.  
Granted my experience in the programming world may be considered short to some, but I have never worked for anyone or any company so far who considers faster to be better over quality.  I can't believe that is even posted...
I know. This is just how it works in business.
I work for an ISP so you really can't generalize like that "This is jus how it works in business".  Maybe thats true for you, but not for all of us thank god.

Aeros
This is not quality.
Spending hours for a feature which helps user to save only miliseconds is useless I think.
This is wasting time. Sometimes programmer should think in this way. I have so many experiences on this issue, you spend days for something but user never see this, may be never use this.
I stand by my previous comment.
Ask a user which one is better?
Two programs working or one program looks very cool.
You can have both, its about modular design and growth as a developer in your area.  Just carry a bigger toolbox, don't cheat your users out of the rich UI experience that is available from ASP.NET because your in a hurry.  What a ripoff.
I dont mean that, if you have a toolbox like you said, of course you should use the best looking one.
What I insist is finding the optimum way, not the short.