click anywhere in a row in Gridview

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Amit Sambyal
    New Member
    • Nov 2011
    • 1

    click anywhere in a row in Gridview

    I used the Gridview in my website.
    I want to get the unique id of that row in which we clicked anywhere in the GridView.


    Here is my code.

    Source code:
    Code:
    <Columns>                       
    
       <%--<asp:TemplateField>
        <ItemTemplate>
        <asp:LinkButton ID="select" runat="server" ForeColor="Black" Visible="false" Text="SingleClick" CommandName ="SingleClick" CommandArgument='<%#Eval("id") %>' />
        </ItemTemplate>
    
    </asp:TemplateField>
                     
    
     <asp:TemplateField ItemStyle-VerticalAlign="Top">
        <ItemTemplate ><table><tr><td onclick="javascript:__doPostBack('GridView1$ctl02$ctl00','')" > 
        &nbsp&nbsp<asp:LinkButton ID="Label2" runat="server" CssClass="underline" Text='<%#Eval("title") %>' Font-Bold="True" Font-Size="Medium" ForeColor="#333399" /><br />
         &nbsp;&nbsp;<asp:LinkButton  ID="Label3" runat="server" CssClass="underline"  Text='<%#Eval("location") %>' ForeColor="Green" />  <br />   
        &nbsp;
        <asp:Label ID="Label5"  runat="server"  Text='<%#Eval("Description") %>' CssClass="lighttext1"/> <br />
    Date:- <asp:Label ID="Label4" runat="server" Text='<%#Eval("date") %>' />
        <br /></td></tr></table>
        </ItemTemplate>
    
    <ItemStyle VerticalAlign="Top"></ItemStyle>
      </asp:TemplateField>


    C# code:
    Code:
     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               _singleClickButton = (LinkButton)e.Row.FindControl("select");
               _singleClickButton.ID = e.Row.DataItem("id").ToString();
                // Get the javascript which is assigned to this LinkButton
                string _jsSingle =ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
                // Add this javascript to the onclick Attribute of the row
                e.Row.Attributes["onclick"] = _jsSingle;
               // _singleClickButton = (LinkButton)e.CommandSource;
                _singleClickButton.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
            }
           
        }
        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "this.className='highlight';");
                e.Row.Attributes.Add("onmouseout", "this.className='normal';");
               //e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference( DirectCast(sender, System.Web.UI.Control), "Select$" + e.Row.RowIndex.ToString());
               
            }
        }
    
     protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "SingleClick")
            {
    
                Response.Redirect("showjobs.aspx?id=" + e.CommandArgument.ToString());
            }
        }
    But its only gives the id =0...I want the id from database on which we clicked row in GridView.
    Last edited by Frinavale; Dec 2 '11, 02:09 PM. Reason: Added code tags.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    You're really close :)

    In order to select the full row you need to use a hidden LinkButton within each row of your GridView (as you are).

    This LinkButton will automatically be registered with ASP.NET so that when it is clicked ASP.NET will validate it as a valid postback to the server.

    You need to retrieve the JavaScript responsible for causing the LinkButton's PostBack event and apply that to the row.

    I simplified things a bit by binding the CommandArgument of the LinkButton to the ID of the underlying data in the ASP markup. In the ASP markup I aslo gave the LinkButton an ID = "Select" (you can't do this in the C# code because you use this ID to retrieve the control from the row) and I set the CommandName ="SingleClic k".

    Now all I have to do in the C# code for the GridView's RowDataBound event is retrieve the LinkButton, get the JavaScript that generates the its PostBack event, and apply it to the row.

    The following is the ASP code for my page (called WebForm1.aspx).
    I left AutoGenrateColu mns = True so that you can tell that you can click anywhere in the row to select it.
    Code:
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            body{color:#333333;}
            .highlight{background-color:#FFFACD;}
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:Label ID="selectedRow" runat="server" />
        <asp:GridView ID="GridView1" runat="server" 
            OnRowDataBound="GridView1_RowDataBound"
            OnRowCommand="GridView1_RowCommand" 
            CellPadding="4" GridLines="None">
             <Columns>
                <asp:TemplateField ItemStyle-VerticalAlign="Top">
                    <ItemTemplate>
                        <asp:LinkButton ID="Label2" runat="server" CssClass="underline" Text='<%#Eval("title") %>'
                            Font-Bold="True" Font-Size="Medium" ForeColor="#333399" />
                        <br />
                        <asp:LinkButton ID="Label3" runat="server" CssClass="underline" Text='<%#Eval("location") %>'
                            ForeColor="Green" />
                        <br />
                        &nbsp;
                        <asp:Label ID="Label5" runat="server" Text='<%#Eval("Description") %>' CssClass="lighttext1" />
                        <br />
                        Date:-
                        <asp:Label ID="Label4" runat="server" Text='<%#Eval("date") %>' />
                        <br />
                        <asp:LinkButton ID="Select" CommandName="SingleClick" CommandArgument='<%#Eval("id") %>'
                            runat="server" Text="select" Style="display: none;" />
                    </ItemTemplate>
                    <ItemStyle VerticalAlign="Top"></ItemStyle>
                </asp:TemplateField>
            </Columns>
           
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
        </form>
    </body>
    </html>

    The following is the C# code for my page.
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            private System.Data.DataTable data;
            protected void Page_Load(object sender, EventArgs e)
            {
                if (Session["data"] == null)
                {
                    data=RetrieveData();
                    Session["data"] = data;
                }
                else
                {
                    data = (System.Data.DataTable)Session["data"];
                }
            }
    
            void Page_PreRender(object sender, EventArgs e)
            {
                GridView1.DataSource = data;
                GridView1.DataBind();
            }
    
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    LinkButton SelectRow = (LinkButton)e.Row.FindControl("Select");
                    String jsSingleClick = Page.ClientScript.GetPostBackClientHyperlink(SelectRow, "");
                    e.Row.Attributes.Add("onclick", jsSingleClick);
    
                    e.Row.Attributes.Add("onmouseover", "this.className='highlight';");
                    e.Row.Attributes.Add("onmouseout", "this.className='';");
                }
            }
    
            protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "SingleClick")
                {
                    selectedRow.Text = "Selected item ID: " + e.CommandArgument.ToString();
                    //Response.Redirect("showjobs.aspx?id=" + e.CommandArgument.ToString());
                }
            }
    
    
            private System.Data.DataTable RetrieveData()
            {
                System.Data.DataTable dt;
                dt = new System.Data.DataTable();
                dt.Columns.Add(new System.Data.DataColumn("id", typeof(String)));
                dt.Columns.Add(new System.Data.DataColumn("title", typeof(String)));
                dt.Columns.Add(new System.Data.DataColumn("location", typeof(String)));
                dt.Columns.Add(new System.Data.DataColumn("Description", typeof(String)));
                dt.Columns.Add(new System.Data.DataColumn("date", typeof(DateTime)));
                for (int i = 1; i < 11; i++)
                {
                    System.Data.DataRow dr = dt.NewRow();
                    dr[0] = i * 11;
                    dr[1] = "Title " + i.ToString();
                    dr[2] = "Location " + i.ToString();
                    dr[3] = "Description " + i.ToString();
                    dr[4] = DateTime.Now;
                    dt.Rows.Add(dr);
                }
                return dt;
            }
        }
    }
    Happy Coding!

    -Frinny
    Last edited by Frinavale; Dec 2 '11, 03:49 PM.

    Comment

    Working...