I have three textboxes a GridView with three columns Roll,name & marks, I want that when the user enter data in three textboxes & click on button,then the data added to GridvIew Columns. Foll code Add the Data to database.

using System.Data.SqlClient; 

public partial class _Default : System.Web.UI.Page 
{
    
SqlConnection conn =new SqlConnection (ConfigurationManager.ConnectionStrings["Connection"].ConnectionString ) ;
string query;
SqlCommand cmd;


    protected void Button1_Click(object sender, EventArgs e)
    {

        try
        {
            query = "Insert into Testing_ViewState values(@Roll,@Name,@Marks)";
            cmd = new SqlCommand(query, conn);
            cmd.Parameters.AddWithValue("@Roll", txtRoll.Text);
            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Parameters.AddWithValue("@Marks", txtmarks.Text);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message.ToString();
        }
    }

   
}

You can get data back using a select statement,store it in dataset,
set datasource of grid view as the dataset,then use databind.

You've got a couple of options. If the data in the able isn't very large and you're not worried about net traffic, draw the info back out of the database once its saved (thats all of the info) and databind the gridview to the dataset again. But that is lazy and wasteful.

Secnd option is to create a datarow object, add 3 columns to it, enter the textbox data to the relevant column and then add the row to the dataset. Databind the dataview again and it'll update with the new information. The gridview and the database will then match each other and you've avoided another round trip to the server.

Hope that helps,

Below is the code to attach text boxes values to datagrid.Initially i have made the gridview visible=false.Include in your submit button click event

DataTable dt = new DataTable();
        DataColumn ColName = new DataColumn("Name");
        DataColumn ColRoll = new DataColumn("Roll");
        DataColumn ColMarks = new DataColumn("Marks");

        dt.Columns.AddRange(new DataColumn[] { ColName, ColRoll, ColMarks });

        DataRow dr = dt.NewRow();


        dr["Name"] = txtName.Text;
        dr["Roll"] = txtRoll.Text;
        dr["Marks"] = txtMarks.Text;

        dt.Rows.Add(dr);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        GridView1.Visible = true;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.