My GridView displays a list of names. On double clicking the name, the name should be set in a textbox. This should happen without any postback. We will use client side scripts for the OnDblClick
event handler.
To set client side event handlers, use the RowCreated
event of GridView.
<asp:TextBox ID="txtSearch" runat="server"/> <asp:GridView ID="gvMain" runat="server" AutoGenerateColumns="false" OnRowCreated="gvMain_RowCreated"> <Columns> <asp:BoundField HeaderText="Name" DataField="Name" /> </Columns> </asp:GridView>
RowCreated
event handler sets the OnDblClick
event handler. We pass the row index to the event handler.
protected void gvMain_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("OnDblClick", "setSearch(" + e.Row.RowIndex + ");"); } }
In the client side, we have the setSearch
function. It handles the OnDblClick
event of the GridViewRow
. We get the table. From the table, we get the table row using the row index. Use cells collection for getting to the right column. In our case, name is available in the first column. Get the name from the innerText
property. We set the name as the TextBox value.
function setSearch(row) { var tbl = document.getElementById("gvMain"); var txt = document.getElementById("txtSearch"); txt.value = tbl.rows[row+1].cells[0].innerText; }
All of this is accomplished by plain old JavaScript. We did not use jQuery. It is possible to write the same code with jQuery. The selector for retrieving the name from the table cell is challenging. I will leave that as an exercise to the reader.