📜  c# asp.net gridview selected row unselect - C# (1)

📅  最后修改于: 2023-12-03 15:29:45.222000             🧑  作者: Mango

C# ASP.NET GridView Selected Row Unselect

Introduction

This guide will show you how to unselect a selected row in an ASP.NET GridView using C#.

Prerequisites
  • Knowledge of C# and ASP.NET
  • A basic understanding of GridViews
Steps
  1. First, add a GridView control to your ASP.NET page.

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Age" HeaderText="Age" />
        </Columns>
    </asp:GridView>
    
  2. Populate the GridView with data from your database or other data source.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }
    
    private void BindGridView()
    {
        DataTable dt = new DataTable();
        // Populate DataTable with data from database or other data source
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    
  3. Add an event handler for the OnSelectedIndexChanged event to handle when a row is selected.

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Do something when a row is selected
    }
    
  4. To unselect the currently selected row, simply call the ClearSelection() method of the GridView.

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView gridView = (GridView)sender;
    
        if (gridView.SelectedIndex > -1)
        {
            // Do something with the selected row
            // ...
    
            // Unselect the row
            gridView.ClearSelection();
        }
    }
    
Conclusion

That's it! Now you know how to unselect a selected row in an ASP.NET GridView using C#. You can use this knowledge to build more complex functionality and improve the user experience of your application.