Add row to Asp.Net GridView

Adding rows dynamically to a GridView in ASP.NET provides flexibility in managing data display, especially when dealing with user-generated content or temporary data. This blog post will demonstrate how to dynamically add rows to a GridView using C# in ASP.NET.

Step-by-Step Guide:

  1. Initializing the DataTable: Before populating the GridView with data, we need to initialize a DataTable to hold the data. The DataTable will mimic the structure of the data to be displayed in the GridView.

    DataTable employeeTable = new DataTable();
    employeeTable.Columns.Add("Name", typeof(string));
    employeeTable.Columns.Add("Email", typeof(string));
    employeeTable.Columns.Add("Age", typeof(int));
    employeeTable.Columns.Add("Country", typeof(string));
    
  2. Binding Initial Data to GridView: On the page load event (ensuring it's not a postback), retrieve data from the database and bind it to the GridView.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Retrieve data from database and bind it to the GridView
            BindInitialData();
        }
    
     protected void BindInitialData()
     {
         using (SqlConnection connection = new SqlConnection(connectionString))
         {
             // SQL query to select data from Employee table
             string query = "SELECT Id, Name, Email, Age, Country FROM Employee";
    
             using (SqlCommand command = new SqlCommand(query, connection))
             {
                 SqlDataAdapter adapter = new SqlDataAdapter(command);
                 adapter.Fill(employeeTable);
    
                 // Bind DataTable to GridView
                 GridView1.DataSource = employeeTable;
                 GridView1.DataBind();
             }
         }
     }
    }
    
  3. Adding Rows Dynamically: To add a new row to the GridView dynamically, we'll manipulate the DataTable associated with the GridView. This allows us to add rows without affecting the underlying data source.

     protected void btnAddRow_Click(object sender, EventArgs e)
     {
         DataRow newRow = employeeTable.NewRow();
         newRow["Name"] = "New Employee";
         newRow["Email"] = "[email protected]";
         newRow["Age"] = 20;
         newRow["Country"] = "UK";
    
         // Add the new row to the DataTable
         employeeTable.Rows.Add(newRow);
    
         // Rebind the DataTable to the GridView
         GridView1.DataSource = employeeTable;
         GridView1.DataBind();
    
         // Save DataTable in ViewState to maintain its state across postbacks
         ViewState["EmployeeTable"] = employeeTable;
     }
    
  4. Maintaining State Across Postbacks: To ensure that the added rows persist across postbacks, we'll store the DataTable in ViewState.

    ViewState["EmployeeTable"] = employeeTable;
    

    On subsequent postbacks, we'll retrieve the DataTable from ViewState to maintain its state.

Dynamically adding rows to a GridView in ASP.NET offers a flexible way to manage data display without altering the underlying data source. By following the steps outlined in this blog post, you can easily implement dynamic row addition functionality in your ASP.NET web applications.

Code Example: Below is the complete code example demonstrating how to dynamically add rows to a GridView in ASP.NET:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
             <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
             <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
             <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
         </Columns>
     </asp:GridView>
 <asp:Button ID="btnAddRow" runat="server" Text="Add New Row" OnClick="btnAddRow_Click" />
    public partial class Contact : Page
    {
        // Connection string to your SQL Server database
        string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        // DataTable to store data from the Employee table
        DataTable employeeTable = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {


            // Initialize DataTable and bind data to GridView on initial load
            if (ViewState["EmployeeTable"] == null)
            {
                InitializeDataTable();
                BindInitialData();
            }
            else
            {
                employeeTable = (DataTable)ViewState["EmployeeTable"];
                GridView1.DataSource = employeeTable;
                GridView1.DataBind();
            }

        }

        protected void InitializeDataTable()
        {
            // Add columns to the DataTable
            employeeTable.Columns.Add("Name", typeof(string));
            employeeTable.Columns.Add("Email", typeof(string));
            employeeTable.Columns.Add("Age", typeof(int));
            employeeTable.Columns.Add("Country", typeof(string));
        }

        protected void BindInitialData()
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // SQL query to select data from Employee table
                string query = "SELECT Id, Name, Email, Age, Country FROM Employee";

                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(employeeTable);

                    // Bind DataTable to GridView
                    GridView1.DataSource = employeeTable;
                    GridView1.DataBind();
                }
            }
        }

        protected void btnAddRow_Click(object sender, EventArgs e)
        {
            DataRow newRow = employeeTable.NewRow();
            newRow["Name"] = "New Employee";
            newRow["Email"] = "[email protected]";
            newRow["Age"] = 20;
            newRow["Country"] = "UK";

            // Add the new row to the DataTable
            employeeTable.Rows.Add(newRow);

            // Rebind the DataTable to the GridView
            GridView1.DataSource = employeeTable;
            GridView1.DataBind();

            // Save DataTable in ViewState to maintain its state across postbacks
            ViewState["EmployeeTable"] = employeeTable;
        }

    }
}
 
Asp.Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
6 + 8 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice