On gridview row mouseover, I would like to display row data in another label

Starwfanatic picture Starwfanatic · Aug 29, 2011 · Viewed 8.7k times · Source

I would like to display the details of a gridview row in another panel when the user mouses over the row. I doubt it is possible through the code behind, so I am looking to use javascript.

for this simple example, I would like to display the id and name of the user in "lblIdDetail" and "lblNameDetail" when the row is moused over:

 <asp:GridView ID="GridView1" runat="server" EnableModelValidation="True" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID="lblId" Text=<%# Bind("id") %> runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID="lblName" Text=<%# Bind("name") %> runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Panel ID="pnlDetails" runat="server">
        <asp:Label ID="Label1" runat="server" Text="The hovered Id is: "></asp:Label>
        <asp:Label ID="lblIdDetail" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label3" runat="server" Text="The hovered name is: "></asp:Label>
        <asp:Label ID="lblNameDetail" runat="server" Text="Label"></asp:Label>
    </asp:Panel>

To fill the grid with dummy data:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable sampleData = new DataTable();
            sampleData.Columns.Add("id");
            sampleData.Columns.Add("name");


            sampleData.Rows.Add("1", "Dave");
            sampleData.Rows.Add("2", "John");
            sampleData.Rows.Add("3", "Jacob");
            sampleData.Rows.Add("4", "Smith");

            GridView1.DataSource = sampleData;
            GridView1.DataBind();
        }
    }

I am very inexperienced using javascript, so I would appreciate as detailed an answer as possible. Thanks :-)

Answer

James Johnson picture James Johnson · Aug 29, 2011

You can add a mouseover event in the RowDataBound event, like this:

//pass the needed row contens into showContents
e.Row.Attributes["onmouseover"] = "showContents(arg1, arg2, arg3)"; 

I would add data keys for the columns you want to display in the labels, pull the values in the RowDataBound event, and pass them into the showContents JS function.