I think code can do better idea than description. check the snippet.
- protected void Button1_Click(object sender, EventArgs e)
- {
- //identifying button
- Button gridBtn = (Button)sender;
- //selecting grid row
- GridViewRow gridRow = (GridViewRow)gridBtn.NamingContainer;
- //setting Index
- int selectedIndex = gridRow.DataItemIndex;
- // Setting Selected Index of GridView1
- GridView1.SelectedIndex = selectedIndex;
- //firing selected Index changed if you need
- //here I used to change color of selected rows
- GridView1_SelectedIndexChanged(GridView1, EventArgs.Empty);
- if (gridBtn != null)
- {
- //changing button text[/color]
- if (gridBtn.Text == "DeSelect")
- { gridBtn.Text = "Select"; }
- else
- { gridBtn.Text = "DeSelect"; }
- }
- }
- protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
- {
- int sIndex = GridView1.SelectedIndex;
- if (GridView1.Rows[sIndex].BackColor == System.Drawing.Color.Red)
- {
- GridView1.Rows[sIndex].BackColor = System.Drawing.Color.White;
- }
- else
- {
- GridView1.Rows[sIndex].BackColor = System.Drawing.Color.Red;
- }
- }
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:
impractical
Post a Comment