Library tutorials & articles

Web Forms DataGrid and DataSet Programming

Inserting a New Row

Although the DataGrid does not have built in support for INSERTs, the DataSet and SqlDataAdapter can help automate the process. The SqlDataAdapter will automatically generate the necessary SQL statement to INSERT a new row into the underlying database table. In this project, text boxes are used to gather information about the new row. This information is then added to the dataset and and the dataset is then updated, automatically inserting the new row into the underlying database table. Note that the same text boxes are also used to filter the data grid.

SqlDataAdapter Generates the INSERT Statement

You don't need to write the SQL INSERT statement. It is generated automatically by the SqlDataAdapter wizard. If you expand the hidden wizard generated code in WebForm1.aspx.cs you can see the auto generated SQL statements:

private void InitializeComponent()
{
  ...
  this.sqlDataAdapter1.InsertCommand = this.sqlInsertCommand1;
  ...
  // sqlInsertCommand1
  //
  this.sqlInsertCommand1.CommandText = @"INSERT INTO authors(au_id, au_lname, au_fname, phone, address, city, state, zip, contract)
  VALUES (@au_id, @au_lname, @au_fname, @phone, @address, @city, @state, @zip, @contract);
  SELECT au_id, au_lname, au_fname, phone, address, city, state, zip, contract FROM authors WHERE (au_id = @au_id) ORDER BY au_id";
  this.sqlInsertCommand1.Connection = this.sqlConnection1;
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@au_id", System.Data.SqlDbType.VarChar, 11, "au_id"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@au_lname", System.Data.SqlDbType.VarChar, 40, "au_lname"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@au_fname", System.Data.SqlDbType.VarChar, 20, "au_fname"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@phone", System.Data.SqlDbType.VarChar, 12, "phone"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@address", System.Data.SqlDbType.VarChar, 40, "address"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@city", System.Data.SqlDbType.VarChar, 20, "city"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@state", System.Data.SqlDbType.VarChar, 2, "state"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@zip", System.Data.SqlDbType.VarChar, 5, "zip"));
  this.sqlInsertCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@contract", System.Data.SqlDbType.Bit, 1, "contract"));
  //
  ...
}

Adding the INSERT Event Handler

Use the IDE to drag and drop the appropriate text boxes and a button onto the form. Then rename the text boxes and buttons. For example:

textBoxLast
buttonAdd

If you double click on the "Add" button in the design view, the IDE will automatically register the button with an event handler and create a new empty event handler in the file WebForm1.aspx.cs. Here is the automatically generated registration code in the hidden "InitializeComponent" method:

this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);

The IDE generates an empty "buttonAdd_Click" event handler. Here is our fully implemented event handler:

protected void buttonAdd_Click(object sender, System.EventArgs e)
{
    string debug= "No errors on INSERT.";
    // Insert new row into the dataset table
    try
    {    
        DataRow dr= dataSet11.authors.NewRow();
        dr["au_id"]= textBoxID.Text;
        dr["au_lname"]= textBoxLast.Text;
        dr["au_fname"]= textBoxFirst.Text;
        dr["address"]= textBoxAddress.Text;
        dr["city"]= textBoxCity.Text;
        dr["state"]= textBoxState.Text;
        dr["phone"]= textBoxPhone.Text;
        dr["zip"]= textBoxZip.Text;
        dr["contract"]= textBoxContract.Text;
        dataSet11.Tables[0].Rows.Add(dr);
        sqlDataAdapter1.Update(dataSet11);
    }
    catch (Exception exc)
    {
        debug= exc.Message;
    }
    // Refresh the grid
    DataGrid1.EditItemIndex = -1;
    ResetPageIndex(DataGrid1, view);
    DataGrid1.DataBind();
    textBoxMessage.Text= debug;
}

This code simply creates a new DataRow and then fills the row with data from the text boxes. The data set is typed so that the appropriate conversion is attempted for each data assignment. Note that the data assignments are wrapped in a try catch construct. If the user enters an illegal Boolean value such as "no" in the "contract" text box, an exception will be thrown on the line:

dr["contract"]= textBoxContract.Text;

Here is the exception message:

"System.FormatException: String was not recognized as a valid Boolean.
   at System.Boolean.Parse(String value)"

Wrapping the call in try catch allows you to exit the function without calling "Update". The exception message is then returned to the user in a multi-line text box. If the data assignments succeed, the row is then added to the data set:

dataSet11.Tables[0].Rows.Add(dr);

Finally, the changes to the data set are written back to the database by calling:

sqlDataAdapter1.Update(dataSet11);

Once a new row has been added to the data set, the auto generated INSERT statement will be used to insert the new row into the database. Again, note that you should wrap the Update() call in try catch, and notify the user if the Insert failed. At the end of the event handler, the data grid is refreshed form the data set by calling "DataBind" so that any successful insert is reflected in the data grid:

// Refresh the grid
DataGrid1.EditItemIndex = -1;
ResetPageIndex(DataGrid1, view);
DataGrid1.DataBind();

Note: An INSERT could fail for a number of reasons. The primary key may already exist. The data may conflict with a column constraint. The data may be missing a required value (Column NOT NULL).

Comments

  1. 26 Jan 2006 at 14:50
    How could i do all this with untyped dataset from xml source? (no find methods etc..)
    Vjero
  2. 23 Nov 2005 at 14:26

    hi
    hey ppl i m   inserting some data manually in a dataview then i m sorting that dta via dataview.sort , sorting is taking place perfectly here but when i embed this data into a word document  then  i found that data is not  in sorted order as this supposed to be but it is in order in which it had typed...........so guys if u  have have any solution of this problem  then plz  mail me at aman_105@rediffmail.com

  3. 10 Nov 2005 at 09:33

    hello
     I am converting C#.net code into vb.net code .
     Sorting ASC or DESC  is not working .
     while degugging ,code work fine but i think some how dataset is not getting refreshed.
     I have commented these line  'view.RowFilter = lastFilter' .Is it require for sorting
     Execpt that everything is same
      please help me out .
                                                Thanks            
     

  4. 30 Jun 2005 at 02:13

    Hi.


    I dont know if this only a problem of mine, but when I hit a sort column the DataGridSortCommand happens twice.


    Should this happen? In my case it happens and so all the code in that event doesnt work properly...


    Could some help me out on this one?


    TIA,
    C.C.

  5. 10 Nov 2004 at 09:24
    How do I obtain ResetPageIndex? It is unknown to my installation of .NET or at least to the libraries I am using.
  6. 01 May 2004 at 12:13

    Jeff,


    Thanks a bunch!  I am new to ASP.NET programming and it was having a devil of a time getting my datagrid to sort -- your example provided the one missing link: the DataSource property should have been set to the view and not the dataset! Tanx again.


    --Babak

  7. 01 Jan 1999 at 00:00

    This thread is for discussions of Web Forms DataGrid and DataSet Programming.

Leave a comment

Sign in or Join us (it's free).

Jeff Louie

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

We'd love to hear what you think! Submit ideas or give us feedback