Jitesh Byahut 2/25/2014 10916

Selected Index Changing Event In GridView In Asp.Net

Here we are binding a GridView in Asp.Net and C#.

Points Of Remember:

1. Fire GridView's SelectedIndexChanging event.

2. Add namespace System.Data and System.Data.SqlClient in your C# page.

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Selected Index Changing event in GridView in Asp.Net</title>

</head>

<body>

  <form id="form1" runat="server">

    <div>

      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"

       OnSelectedIndexChanging="GridView1_SelectedIndexChanging" AutoGenerateSelectButton="True">

            <Columns>

                <asp:BoundField DataField="Name" HeaderText="Name" />

                <asp:BoundField DataField="Branch" HeaderText="Branch" />

                <asp:BoundField DataField="City" HeaderText="City" />

            </Columns> 

      </asp:GridView>

 

     <table>

     <tr><td>Name</td><td><asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td></tr>

     <tr><td>Branch</td><td><asp:TextBox ID="txt_branch" runat="server"></asp:TextBox></td></tr>

     <tr><td>City</td><td><asp:TextBox ID="txt_city" runat="server"></asp:TextBox></td></tr>

     </table>

       

    </div>

  </form>

</body>

</html>

C# Codes :

using System.Data;

using System.Data.SqlClient;

 

public partial class GridView : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGridView();

        }

    }

    //method for binding GridView

    protected void BindGridView()

    {

        DataTable dt = new DataTable();

        SqlConnection con = new SqlConnection(@"Data Source=JITESH-PC\SQL;Initial

                   Catalog=db_Student;Integrated Security=True");

        SqlDataAdapter da = new SqlDataAdapter("Select name,branch,city from tbl_student", con);

        con.Open();

        da.Fill(dt);

        con.Close();

 

        if (dt.Rows.Count > 0)

        {

            GridView1.DataSource = dt;

            GridView1.DataBind();

        }

    }

 

    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)

    {

        txt_name.Text = GridView1.Rows[e.NewSelectedIndex].Cells[1].Text;

        txt_branch.Text = GridView1.Rows[e.NewSelectedIndex].Cells[2].Text;

        txt_city.Text = GridView1.Rows[e.NewSelectedIndex].Cells[3].Text;

    }

 

}

View output :

demo


Please give your feedback for improving this page