The tips and tricks of this article are: Use JavaScript to select the GridView line.
Here's what we do with JavaScript.
We can simulate the selected row by calling the Javascirpt function to change the background color of the clicked row, where we need to declare a hidden field and obtain the ID of the GridView line from JS. In the Select/delete event, you can get the ID of the selected row from the hidden field to complete some of the required functions.
Step One: Add the GridView Control and a button to the page, hide the field
<input id="hdnEmailID" type="hidden"
value="0" runat="server" name="hdnEmailID" />
<asp:GridView ID="gvUsers" runat="server"
AutoGenerateColumns="False"
OnRowDataBound="gvUsers_RowDataBound">
<Columns>
<asp:BoundField DataField="Email" HeaderText="邮件" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="姓名" ReadOnly="True" />
</Columns>
</asp:GridView>
<asp:Button ID="btnSelect" runat="server"
OnClick="btnSelect_Click" Text="Select" />
Step two: Write the JS function to get the ID of the selected row, and change the background color
<script language="javascript" type="text/javascript">
var lastRowSelected;
var originalColor;
function GridView_selectRow(row, EmailID)
{
var hdn=document.form1.hdnEmailID;
hdn.value = EmailID;
if (lastRowSelected != row)
{
if (lastRowSelected != null)
{
lastRowSelected.style.backgroundColor = originalColor;
lastRowSelected.style.color = 'Black'
lastRowSelected.style.fontWeight = 'normal';
}
originalColor = row.style.backgroundColor
row.style.backgroundColor = 'BLACK'
row.style.color = 'White'
row.style.fontWeight = 'normal'
lastRowSelected = row;
}
}
function GridView_mouseHover(row)
{
row.style.cursor = 'hand';
}
</script>
The next step is to bind the data and do it yourself.
Step three: Add the JS function call to the RowDataBound event.
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.ID = e.Row.Cells[0].Text;
e.Row.Attributes.Add("onclick",
"GridView_selectRow(this,'" + e.Row.Cells [0].Text + "')");
e.Row.Attributes.Add("onmouseover", "GridView_mouseHover(this)");
}
}
Step Fourth: Completing the button event
In the Select/Delete button Click event we can use the Hdnemailid.value method to get the row ID. Then use the ID to complete the operation; I just output the value here for demonstration.
protected void btnSelect_Click(object sender, EventArgs e)
{
Response.Write(hdnEmailID.Value);
}
OK, this technique is introduced here, everybody try!