Adsence750x90

Saturday, September 4, 2010

Select GridView Row without using Select button

This code snippet Illustrate How to Select GridView Row without using Select Command button.
I think code can do better idea than description. check the snippet.


  1. protected void Button1_Click(object sender, EventArgs e)  
  2.     {  
  3.         //identifying button  
  4.         Button gridBtn = (Button)sender;  
  5.        //selecting grid row  
  6.         GridViewRow gridRow = (GridViewRow)gridBtn.NamingContainer;  
  7.        //setting Index  
  8.         int selectedIndex = gridRow.DataItemIndex;  
  9.        // Setting Selected Index of GridView1  
  10.          GridView1.SelectedIndex = selectedIndex;  
  11.         //firing selected Index changed if you need  
  12.         //here I used to change color of selected rows  
  13.          GridView1_SelectedIndexChanged(GridView1, EventArgs.Empty);  
  14.         if (gridBtn != null)  
  15.         {  
  16.            //changing button text[/color]  
  17.             if (gridBtn.Text == "DeSelect")  
  18.             { gridBtn.Text = "Select"; }  
  19.             else  
  20.             { gridBtn.Text = "DeSelect"; }  
  21.         }  
  22.   
  23.     }  
  24.     protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)  
  25.     {  
  26.         int sIndex = GridView1.SelectedIndex;  
  27.         if (GridView1.Rows[sIndex].BackColor == System.Drawing.Color.Red)  
  28.         {  
  29.             GridView1.Rows[sIndex].BackColor = System.Drawing.Color.White;  
  30.         }  
  31.         else  
  32.         {  
  33.             GridView1.Rows[sIndex].BackColor = System.Drawing.Color.Red;  
  34.         }  
  35.   
  36.     }  


ASPX section

I add One Button field as Template field. and add Button text as "Select". when you click on select button in GridView, the selected Row become Red color.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1">
            <columns>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Category" HeaderText="Category"
                    SortExpression="Category" />
                <asp:BoundField DataField="Tags" HeaderText="Tags" SortExpression="Tags" />
                <asp:TemplateField>
                    <itemtemplate>
                        <asp:Button ID="Button1" runat="server" Text="Select" onclick="Button1_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>


Preview of Output
You can Select or Deselect GridView Rows.






Thank you for Reading this code snippet.
Feel Free to comment. if you have any doubts let me know.

1 comment:

Anonymous said...

impractical