How to enable a GridView to make inserts ASP.NET

READ THIS BEFORE!!:

I suggest you take the time to read every word on this because you will not need
to search again, everything is explained on the following lines.

Some day you will need to enable a GridView to make insertions into a DataBase,
to accomplish this you will need to do few steps in order to make it work.
(For the example, ill be only focused on the insert command)

On this example im using an SqlDataSource object provided with the framework 2.0,
but you can use your own method to work on (continue reading, you will see when you
can use your own method if is the case).

First of all drag & drop a Grid View into your web form, on the smart tag (the small
arrow in the upper right corner) and select “choose data source”.

Smart tag

Here you have two options to configure your datasource, using raw sql commands or using
stored procedures, doesnt matter wich one you choose (i prefer stored procedures) and which
commands (select/insert/update/delete).

Well, first of all do the “DataBound” to populate your Grid, after that you will
see the columnames on it. Enable Edit, Update and Delete options!!
Then click on the smart tag and select “Edit Columns”.

Do the proper changes on your columns and then on every column click on “Convert to TemplateField”,
once you did this to your columns click on OK to close the window and apply the changes.

Now click again on the smart tag and select “Edit Templates”; A new view of the Grid will
be shown where you can edit every mode of it.

Templates, we want the foother

Click on the combo box and select “Column[1] – “, then you will see the
templates for every mode on your grid; you will see the “FooterTemplate” object empty, here
is where you will add the control needed; on this case we will put a TextBox naming it
“txtColumn1.txt” and for validation we will insert a RequiredFieldValidator to be sure
the user doesnt left the field empty.

Dont forget to set the RequiredFieldValidator’s ControlToValidate property to txtColumn1 and
the ValidationGroup property to “vgInsert”.. you have to do the same on every column where
you need to capture data, EXCEPT the last column where are the buttons or link buttons

On the last column add 3 link buttons, labeled “New”, “Cancel”, and “Insert”, on the first
two LinkButtons change the property CausesValidation to false, and be sure the Insert LinkButton
has it on “true”, also on the Insert LinkButton set the ValidationGroup to “vgInsert”.

Because on the initial view of the GridView, we only want to see the New button, dont
forget to set the visible property of Insert and Cancel button to false.

Properties of the template

This will cause the first two buttons doesnt validate the fields, and the Insert button
will perform the validation using the validators on the elements!.

Double click on the link button to create the event handler for each of them, it will look
like this:

protected void lbNew_Click(object sender, EventArgs e)
{

}

Ive made a small function to clean and show or hide the fields, you will need to add
or remove your own fields, here is the example:

protected void Show(bool visible)
{
//find the insert button on the GridView (gv)
LinkButton Insert = (LinkButton)gv.FooterRow.FindControl("lbInsert");

//find the Cancel button on the GridView (gv)
LinkButton Cancel = (LinkButton)gv.FooterRow.FindControl("lbCancel");

LinkButton New = (LinkButton)gv.FooterRow.FindControl("lbNew");

//find the TextBoxes on the GV
TextBox Column1 = (TextBox)gv.FooterRow.FindControl("txtColumn1");
TextBox Column2 = (TextBox)gv.FooterRow.FindControl("txtColumn2");

//Now set their propierties, based on the parameter "visible"
New.Visible = !visible;
Insert.Visible = visible;
Cancel.Visible = visible;

Column1.Text = string.Empty;
Column2.Text = string.Empty;
Column1.Visible = visible;
Column2.Visible = visible;
}

Once we have this function, change your event handlers to look like this:

protected void lbNew_Click(object sender, EventArgs e)
{
Show(true);
}
protected void lbCancel_Click(object sender, EventArgs e)
{
Show(false);
}

Now lets see the important function here, the Insert:

protected void lbInsert_Click(object sender, EventArgs e)
{
// As i said, you can use your own method to perfom the insertion of the
// data, using your Data Acces Layer, or direct SqlCommand on this function,
// to do that just replace the code below with your own, dont forget to re-bind
// your grid to show the latest data.

// We find the controls to extract its data
string Column1 = ((TextBox)gv.FooterRow.FindControl("txtColumn1")).Text;
string Column2 = ((TextBox)gv.FooterRow.FindControl("txtColumn2")).Text;

// We set the parameters for the datasource, on this case for the stored procedures, but
// also can be parameters of a raw query.
// NOTICE, here the parameters doesnt go with a "@"
demoDataSource.InsertParameters.Add(new Parameter("parameter1", TypeCode.String, Column1));
demoDataSource.InsertParameters.Add(new Parameter("parameter2", TypeCode.String, Column2));

// Call the insert method of the DataSource
demoDataSource.Insert();

// Re bind the Grid to show the changes
gv.DataBind();

// Hide the controls
Show(false);
}

To catch the exception, on this case look into the Inserted event of the SqlDataSource (e.Exception)

If you get an exception of many parameters sent to the insert method, check the InsertCommand on the
SqlDataSource and remove every parameter on it (we are sending them programatically).

I hope this help you, if you need help, have a suggestion or even want to say thanks pls drop me few lines
here. I can help you on spanish too, its my native language.

Happy Coding!

5 Responses to “How to enable a GridView to make inserts ASP.NET c#”

  1. Jeremy Says:

    Thanks! This is exactly what I was looking for.

  2. Suni Says:

    this is very nice,had lot of information.thanks

  3. SChouinard Says:

    Maybe you won’t even see this comment since the post is more than a year old but how do you show the footer row with the insert stuff in it if there is no item in the datagrid to begin with?

  4. Rohit Says:

    Dude you saved my day

    BUT you forgot to mention
    In GRIDVIEW FooterTemplate is set invisible by default
    That took my half day

    Well this was really for DUMMY developer
    a STEP BY STEP procedure to insert into datagrid

    THANX ALOT MEN

  5. Rijil Says:

    Very good ….


Leave a Reply