Wednesday, 22 February 2012

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




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SelectRow.aspx.cs" 
            Inherits="SelectRow" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" 
               AutoGenerateColumns="False" DataKeyNames="ID"
               Width="200px" AllowPaging="True" 
                   OnRowDataBound="PeopleGridView_RowDataBound">
               <Columns>
                   <asp:BoundField DataField="StringField" 
                              HeaderText="Name" SortExpression="StringField">
                   </asp:BoundField>
               </Columns>
           </asp:GridView>
       </div>
   </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class SelectRow : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetDataSet();
            GridView1.DataBind();
        }

    }
    public DataTable GetDataSet()
    {

        DataTable dt = new DataTable("Company");
        DataRow dr;
        dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
        dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
        dt.Columns.Add(new DataColumn("StringField", typeof(string)));
        for (int i = 0; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i;
            dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
            dt.Rows.Add(dr);
            DataColumn[] Parent_PKColumns = new DataColumn[1];
            Parent_PKColumns[0] = dt.Columns["ID"];
            dt.PrimaryKey = Parent_PKColumns;
            Session["DataSource"] = dt;
        }

        return dt;
    }
    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.GridView1,  
                            "Select$" + e.Row.RowIndex);
        }

    }
}

No comments :