Friday, September 9, 2011

Select a row in an asp:GridView without using a Select Command



ASP.Net's GridViews can be quite useful, but beware of binding them to huge datasets as this has an overhead on the ViewState.
Often you'll want to display a number of columns on each line and row space becomes an issue. What's worse is you then have to create a SELECT command button to be able to access that line's data.
<asp:CommandField ShowInsertButton="true" />
Use the following code on the event OnRowDataBound to eliminate the need for the SELECT command field and save yourself some valuable space.
Here is the HTML to create a GridView, I'm displaying a list of people, and the key for each record is the PERSON_ID.
<asp:GridView ID="PeopleGridView" runat="server" 
    AutoGenerateColumns="False" 
    DataKeyNames="PERSON_ID" 
    DataSourceID="PeopleDataObject" 
    Width="200px" 
    OnRowDataBound="PeopleGridView_RowDataBound" 
    AllowPaging="True">
    <Columns>  
        <asp:BoundField 
            DataField="USER_NAME" 
            HeaderText="Name" 
            SortExpression="USER_NAME" >
        asp:BoundField>
    Columns>
asp:GridView>
The key event to note is the OnRowDataBound, use the following code to create SELECT functionality on the row.
protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.PeopleGridView, "Select$" + e.Row.RowIndex);
        }
    }
Each row will then behave like a link, and when you select one it can drive the behavior of another control(s) on your page, possibly a DetailsView allowing you to INSERT a complete record to the database.

No comments:

Post a Comment