TBogdan
TBogdan

Reputation: 737

Simple Selecting a row from gridview in asp.net web application

I know this question had been asked a hundred times, but I have difficulties implementing different solutions.I need to retrieve a selected row from a grid view in asp.net web application C#.I've done the databinding.I don't want to use edit/update buttons or checkboxe/radio button, just to select it by clicking on the row.Please help, I'm a little stuck, and I would like not 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, "");


        }

Upvotes: 5

Views: 46731

Answers (2)

Saad Qureshi
Saad Qureshi

Reputation: 389

If you are adding a DataSource from code behind file then you have to set property called "AutoGenerateSelectButton " to True . This will enable you to select a row.

Upvotes: 3

Thousand
Thousand

Reputation: 6638

if i get it right, 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 will give you the selected row ID, provided by the DataKeyNames attribute in your .aspx page. This however does require the "Enable Selection" to be checked. (Go to your .aspx page, designer, click your gridview, you should see the "Enable selection" attribute).

Upvotes: 8

Related Questions