Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, "");


        }
like image 957
TBogdan Avatar asked Jun 22 '12 22:06

TBogdan


1 Answers

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).

like image 68
Thousand Avatar answered Nov 15 '22 08:11

Thousand