Saturday, March 11, 2017

GridviewSelectionIndex Change Event in Asp .Net

 This post shows "How to use Gridview SelectionIndexChanging Event in asp .net".For this tutorial I am using Northwnd database cutomer table.Follow this link to download Northwnd database.


Html Tag:

Create a gridview SelecetedIndexChanging Event for your grid.

<form id="form1" runat="server">
    <div>
        <div class="w3-container">
            <h2>GridView Select Index Changed Demo</h2>
            <hr />
        </div>
        <div class="w3-row">
            <div class="w3-col w3-margin-left m6">
                <asp:GridView ID="grdView" runat="server" AutoGenerateColumns="false"
                    OnSelectedIndexChanging="grdView_SelectedIndexChanging"
                    CssClass="w3-table-all w3-small">
                    <Columns>
                        <asp:BoundField HeaderText="CustomerID" DataField="CustomerID" />
                        <asp:BoundField HeaderText="CompanyName" DataField="CompanyName" />
                        <asp:BoundField HeaderText="ContactName" DataField="ContactName" />
                        <asp:ButtonField HeaderText="Action" Text="Select" ControlStyle-CssClass="w3-btn w3-teal w3-small"  CommandName="Select" />
                    </Columns>
                </asp:GridView>
                <br />
                <asp:Label ID="lblStatus" runat="server"></asp:Label>
            </div>
        </div>
    </div>
    </form>

Code Behind:

Inside the grdView_SelectedIndexChanging event we get the currently selected row index and access its cell value using index value.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            BindData();
        }
    }

    private void BindData()
    {
        string sConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(sConnectionString);
        SqlCommand cmd = new SqlCommand("SELECT Top 5 *FROM Customers", conn);
        DataTable dt = new DataTable();
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        sda.Fill(dt);
        grdView.DataSource = dt;
        grdView.DataBind();
    }

    
    protected void grdView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridViewRow grdRow = grdView.Rows[e.NewSelectedIndex];
        lblStatus.Text = "<strong>Customer ID:</strong>" + grdRow.Cells[0].Text + "\n<strong> Company Name:</strong>" + grdRow.Cells[1].Text + "\n <strong>Contact Name:</strong>" + grdRow.Cells[2].Text;
    }

Output:



Download Source Code



No comments:

Post a Comment