Simple row selection from gridview in asp.net web application

I know that this question has been asked a hundred times, but I am having difficulty implementing various solutions. I need to get the selected row from a grid view in an ASP.NET ASP.NET web application. I did data binding. Do not want to use the edit / update buttons or checkbox / radio button, just select it by clicking on the line. Please help, I'm a bit stuck, and I would not want to implement javascript based solutions. Thanks.

if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("OnMouseOver", "this.style.cursor='pointer';this.style.textDecoration='underline';"); e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; e.Row.ToolTip = "Click on select row"; e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(this.SingleSelectGrid, "Select$" + e.Row.RowIndex); LinkButton selectbutton = new LinkButton() { CommandName = "Select", Text = e.Row.Cells[0].Text }; e.Row.Cells[0].Controls.Add(selectbutton); e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(selectbutton, ""); } 
+4
source share
2 answers

if I understood correctly, this should do what you want:

.aspx:

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" onselectedindexchanged="GridView1_SelectedIndexChanged"> 

code behind:

  protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { int index = Convert.ToInt16(GridView1.SelectedDataKey.Value); } 

this should do what you want. index.exe will give you the selected row identifier provided by the DataKeyNames attribute on your .aspx page. However, this requires an “Enable selection” check. (Go to the .aspx page, constructor, click on gridview, you will see the "Enable selection" attribute).

+5
source

If you add a DataSource from the code behind the file, you need to set the AutoGenerateSelectButton "property to True . This will allow you to select a row.

+1
source

All Articles