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,
- <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.
- protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- string code= GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();
- int rowid = Convert.ToInt32(e.Row.RowIndex) + 1;
- string code1= GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString(); ;
- e.Row.Attributes.Add("onclick", "onGridViewRowClick1('" + rowid.ToString() + "','" + codce.ToString() + "','" + code1.ToString() + "')");
- }
- }
Here is the JavaScript to validate the selection
- function onGridViewRowClick1(rowIndex, code, code1) {
- var table = document.getElementById("<%=GridView1.ClientID%>");
- for (var i = 0; i < table.rows.length; i++) {
- if (i % 2 != 1) {
- table.rows[i].style.backgroundColor = '#F2FFFF';
- }
- else {
- table.rows[i].style.backgroundColor = '#E1F4F4';
- }
- }
- RowIndex_GID = rowIndex;
- var invcode = document.getElementById("<%=gridviewselection.ClientID%>");
- code.value = code; ;
-
- var selRow = getClickedRow1(rowIndex);
-
- if (null != selRow) {
- table.rows[rowIndex].style.backgroundColor = '#add8e6';
-
- }
- }
Thanks for reading