GridView Row Selection In ASP.NET

Here we are going to see how to select a row in datagrid when we have mlutiple rows in a GridView. We will be using JavaScript to validate the row selection.
 
Enter the datakeys for the GridView to select the row.
 
Example
 
Datakeys are important,
  1. <asp:GridView ID="GridView1" runat="server" OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="InventoryCode,GidQty" ShowHeaderWhenEmpty="True"></asp:GridView>  
Make the unique column as DatakeyNames.  
 
RowCreated event is used to hold the selected values from the datagrid.
  1. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)  
  2.       {  
  3.           if (e.Row.RowType == DataControlRowType.DataRow)  
  4.           {  
  5.               string code= GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();/
  6.               int rowid = Convert.ToInt32(e.Row.RowIndex) + 1;  
  7.               string code1= GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString(); ;  
  8.               e.Row.Attributes.Add("onclick""onGridViewRowClick1('" + rowid.ToString() + "','" + codce.ToString() + "','" + code1.ToString() + "')");  
  9.           }  
  10.       }   
Here is the JavaScript to validate the selection
  1. function onGridViewRowClick1(rowIndex, code, code1) {  
  2.             var table = document.getElementById("<%=GridView1.ClientID%>");  
  3.              for (var i = 0; i < table.rows.length; i++) {  
  4.                  if (i % 2 != 1) {  
  5.                      table.rows[i].style.backgroundColor = '#F2FFFF'//#E1F4F4  
  6.                  }  
  7.                  else {  
  8.                      table.rows[i].style.backgroundColor = '#E1F4F4';  
  9.                  }  
  10.              }  
  11.              RowIndex_GID = rowIndex;  
  12.              var invcode = document.getElementById("<%=gridviewselection.ClientID%>");  
  13.             code.value = code;  ;  
  14.   
  15.             var selRow = getClickedRow1(rowIndex);  
  16.   
  17.             if (null != selRow) {  
  18.                 table.rows[rowIndex].style.backgroundColor = '#add8e6';  
  19.   
  20.             }  
  21.         }  
Thanks for reading
Ebook Download
View all
Learn
View all