This is how you could create a GridView that has a checkbox in every row and allows you to select multiple rows. The selected rows will change their background color.
First, the GridView markup:
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="False" DataKeyNames="MyFieldName"
EnableViewState="True" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate >
<asp:CheckBox ID="chkSelect" runat="server" onClick='selDesel(this, this.checked)' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="File Name" />
</Columns>
</asp:GridView>
It is important to use the DataKeyNames property to hold the value of a key field.
I assume there is also a Submit button on the page. Now, to determine which rows have been selected, use the following code in the Submit button click event handler:
foreach (GridViewRow row in gv1.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
if (chk != null && chk.Checked)
{
//get the value of data key
string remoteUrl = gv1.DataKeys[row.RowIndex].Value.ToString();
//get the value of the fist column
string name = gv1.Rows[row.RowIndex].Cells[1].Text;
//do something with the values obtained.
}
}
Now, we need to write some JavaScript to change background color on selecting or de-selecting a checkbox:
var selColor = "#8080FF";
var selBorderColor = "#FF80FF";
var selForeColor = "LightCyan";
var origColor ='';
var origBorderColor="";
var origForeColor = "";
function selDesel(chk, chkVal){
//get a reference to a row element
var tr = getParent(chk, "TR");
//we don't want to change the color of the heading row
if(tr.firstChild.nodeName != "TH") {
//if the check box is checked, assign a new value to a style property and remember the old one
if(chkVal){
origColor = tr.style.backgroundColor;
origBorderColor = tr.style.borderColor;
origForeColor = tr.style.color;
tr.style.backgroundColor = selColor;
tr.style.color = selForeColor;
tr.style.borderColor = selBorderColor;
}
else{
tr.style.backgroundColor =origColor;
tr.style.borderColor =origBorderColor;
tr.style.color =origForeColor;
}
}
}
function getParent (elem, parName){
var par = elem;
do {
par = par.parentNode;
}
while (par.nodeName != parName)
return par;
}
To find out how to add a 'Select All' checkbox to the header row, please go here .