Asp net c add to gridview with textbox programmatically but in second click re

ASP.NET is a powerful programming that allows developers to create dynamic web applications. One common task in web development is adding data to a control programmatically. In this article, we will explore how to achieve this using ASP.NET with C#.

To begin, let's assume we have a GridView control on our web page and we want to add data to it when a button is clicked. We will also use a TextBox control to input the data that will be added to the GridView.

First, let's take a look at the ASP.NET code that sets up the GridView and TextBox controls:





In the code above, we have a GridView control with the ID “GridView1” and a TextBox control with the ID “TextBox1”. We also have a Button control with the ID “Button1” that will trigger the event handler when clicked.

Now, let's move on to the C# code that handles the button event and adds the data to the GridView:


protected void Button1_Click( sender, EventArgs e)
{
    string data = TextBox1.Text; // Get the data from the TextBox

     dt = new DataTable(); // Create a new DataTable
    dt.Columns.Add("Data"); // Add a  to the DataTable

    DataRow dr = dt.NewRow(); // Create a new DataRow
    dr["Data"] = data; // Set the value of the column to the data

    dt.Rows.Add(dr); // Add the DataRow to the DataTable

    GridView1.DataSource = dt; // Set the GridView's data source to the DataTable
    GridView1.DataBind(); // Bind the data to the GridView
}

In the code above, we first retrieve the data entered in the TextBox control using the Text property. We then create a new DataTable and add a column to it. Next, we create a new DataRow and set the value of the column to the data entered in the TextBox. Finally, we add the DataRow to the DataTable.

After that, we set the GridView's data source to the DataTable using the DataSource property and call the DataBind method to bind the data to the GridView.

Now, when the button is clicked, the data entered in the TextBox will be added to the GridView.

Conclusion

In this article, we have explored how to add data to a GridView control programmatically using ASP.NET with C#. We have seen how to set up the necessary controls in the ASP.NET code and how to handle the button click event in the C# code. By following , you can easily add data to a GridView in your ASP.NET web application.

Remember to always test your code and handle any potential or exceptions that may . Happy coding!

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents