How to enable a GridView to make inserts ASP.NET c#
September 18, 2007
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”.

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.

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.

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!
Adding JavaScript to ASP.NET Menu control to open a popup window + centered on screen
September 14, 2007
Finally this is my first post about coding on C#, i hope this helps somebody (it worked for me), at least for reference.
The past week ive been working on an ASP.NET app which requires to show a many forms as a PopUp but they needed to be loaded with the Menu control provided on the framework. The control is databound to a sitemap XML file.
Was a little complicated because it needs few steps to make it work but i hope this may help you to make the same and save you few hours trying to figure out how to.
Lets start…
Rigth click over your solution tree, select add new item, and from the window choose a “site map”, then click on OK.
On the file generated you need to add the corresponding entries to your page, but we will use mor XML fields to fulfill our purpuose:
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode title="Root Menu" description="This is the root menu">
<siteMapNode title="Child Menu" description="This is a child menu">
<siteMapNode url="" title="Click on me to open a popup window"
description="This page is cool" heigth="450" width="screen.width - 150"
address="popupme.aspx"/>
<siteMapNode url="form.aspx" title="Click on me to open a normal window"
description="This page is cool"/>
</siteMapNode>
</siteMapNode>
</siteMap>
Once you write the entries, click on save and close it, now look on the menu’s event “MenuItemDataBound”, and write the following on it:
void menuObject_MenuItemDataBound(object sender, MenuEventArgs e)
{
string address = string.Empty;
string heigth = string.Empty;
string width = string.Empty;
string title = string.Empty;
string url = string.Empty;
address = ((SiteMapNode)(e.Item.DataItem))["address"];
heigth = ((SiteMapNode)(e.Item.DataItem))["heigth"];
width = ((SiteMapNode)(e.Item.DataItem))["width"];
title = ((SiteMapNode)(e.Item.DataItem))["title"];
url = ((SiteMapNode)(e.Item.DataItem))["url"];
//we left the url field empty on the sitemap file to know
//this will be a javascript link, so:
if (string.IsNullOrEmpty(url))
{
e.Item.NavigateUrl = "javascript:OpenWindow('" + address + "'," + heigth + "," + width + ",'" + title + "')";
}
else
{
e.Item.NavigateUrl = url;
}
}
Now we are close to the end.. did you noticed there was something missing??!!… yes!, the javascript function to open the popup window, here is the source:
(Dont forget to put it inside the page which will launch the popup windows (the page with the menu control, or the masterpage of it) inside the <HEADER>…</HEADER> tags!
<script language="javascript">;
function OpenWindow(address, heigth, width, title)
{
var winl = (screen.width-width)/2;
var wint = (screen.height-heigth)/2;
var options = "width=" + width;
options += ",height=" + heigth;
options += ",top=" + wint;
options += ",left=" + winl;
options += ",location=no,toolbar=no, menubar=no, scrollbars=1, resizable";
window.open(address, title, options);
}
</script>;
Once when you have this, we need to add a default sitemap provider for the project so the last step is modify your web.config file as its shown here inside the system.web sections:
<system.web>
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider" type="System.Web.XmlSiteMapProvider" siteMapFile="Web.sitemap"/>
</providers>
</siteMap>
</system.web>
Now, you can try to run your App!.
Again this is my first Code post and i hope this helps you, any comments are welcome!















