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!
Microsoft Photosynth
August 11, 2007
Microsoft has made one more acquisition, but this is done particularly entertainment to me, is Photosynth.Its a system that analyzes photographies to construct a three-dimensional model of the object in question, recognizing the patterns they are
compared to become a model, with this is possible progressively to show gigabytes of very high quality graphics with a very good speed downloading times, but the things does not finish there, you can make a very good zoom lens to any taken image, obvious the quality will vary according to the quality with which it has been taken.The user interface and general of the system makes me feel as in GoogleEarth but already in third dimension.
But why you will believe on me!? test it by yourself clicking here, you will need to download the required components to work with Photosynth, personally i prefer to use it with Firefox because i feel it faster.
Ive taken few screen shots to see it by yourself, and in the bottom is the video of the presentation.



Microsoft Regional Architect Forum México 2007
June 16, 2007
The past 14 and 15 of June where the third RAF in México City, this time (my first time there) where focused on S+S (Software plus Services).
The RAF was a high level event which gathered more than 100 key architects of the leading technological industries in the republic.
The introduction text for this where:
“The services are everywhere and they have become into an indispensable artifact of every kind of business’ technical strategies. The global collaboration is directing the organizations to become service providers.
The business applications – software which integrates this into handy processes – are using components of a deeply heterogeneous network and continuously growing of providers. To get the higher provecho of the S + S model we need to answer several fundamental questions about the way of this services should be provided and consumed to reach the objective of our business.”
- How are the applications which consumes external services and what is what the providers requires?
- How is managed and governed a portfolio of services which extends beyond the organizations borders?
- How S+S foments the productivity directed to the peoples and which metamorphosis are suffering the organizations now when the power of this new technologies are available for everyone?
Wednesday 14 of June 2007
The first conference where of Gianpaolo Carraro, he where talking about the “Next generation software, an Architect’s perspective”.
Alberto Borbolla where talking about the Microsoft ESB Implementation instead of Marty Wasznicky (he had problems in some flight connection and couldn’t be present).
Eduardo Kassner where talking about the “Value of an dynamic infrastructure”, showing us an success case of HSBC México made following the ITIL (IT Infrastructure Library, the most widely accepted approach to IT management) Microsoft’s version “Infrastructure Optimization Model” with their 4 stages of maturity and the importance of follow guidelines to improve business reliability.
After this we went to eat at the Thai House, when we finished I went to the demonstration session about “New paradigms of the data access and data manipulation for architects” by Gabriel Esparza Romero. There he showed us how easy is to use the new LINQ to make queries in XML and SQL with the visual studio codename Orcas. This have great potential about using this to get a more OO concept of data and manipulation / querying it to get what we need; Right now I have two applications which could be made more easily using DLINQ.
Eduardo Kassner’s next talk where about the Infrastructure Optimization model, the importance of suit every requirement on each stage of the maturity, reason?, simply; You will not be able to suit higher requirements, processes and control if you don’t suit the fist and basics;
“The Infrastructure Optimization Model helps customers realize dramatic cost savings for their IT infrastructure by moving from an unmanaged environment towards a dynamic environment. Security improves from highly vulnerable in a Basic infrastructure to dynamically proactive in a more mature infrastructure.”

IT infrastructure management changes from highly manual and reactive to highly automated and proactive.
Friday 15 of June 2007
This day the session were shorter but not for that less important, we started with Mark Baciak (is an architect on Microsoft’s Architecture Strategy Team specializing in service orientation and enterprise dynamics) talking about the infrastructure behind a service oriented architecture.
After him Ric Merrifield taked to us about “Getting SOA through Business Value”, unfortunately I couldn’t listen almost anything because I where attending a work call outside the hall.
After this talk, Karthik Ravindran exposed “architecting and implementing user & process centric business applications using the office 2007 system”.
The last session where about “Business architecture to sustenance the competitively of México” by PhD. Ricardo zermeño talking about the current situation of the country against the others in the world and the plan to 15 years to become one of the 20th most important economies of the world by improving the technology and the business governability.
After this, Juan Carlos Lozada closed the event, telling us the statistics and a brief history about the event.
We went to eat at the Thai House again, but I had the luck of being sited with the VIP!, here are the descriptions:
From the left to the right:
Karthik Ravindran, architect in the strategic architecture focused in business applications (Microsoft).
Gabriel Esparza-Romero, Test lead in the C# team, is in charge right now of the LINQ implementation (Microsoft).
Unknown guy
Consultant (nice guy)
Armando Chavez, S. Developer.
And I don’t remember the names of the other 2 guys, but they lead the DOT NET COMMUNITY on the city (INETA).
I’m tired of writing all this, also for searching links to the post, so for a small resume:
This was a great opportunity to have another point of view about Information technology (IT), the perspective about building more efficient, secure, reliable and expandable applications and infrastructure. I got with this a great experience trough sharing and learning from other people and business problems and solutions.
I’m waiting for the next year and be able to give them better feedback and questions regarding architecture and processes.
For those who want to become a business architect AKA software / infrastructure architect, visit the Microsoft’s SKYSCRAPR website, where you will get the introduction and training to become one.
Also to get a subscription to “The Architecture Journal” a publication made by MS to the enterprise architects, or to get more information, go here and suit your needs of knowledge.
















