No Java Required: Write Android Apps in C#

8:32:00 am 0 Comments

XobotOS is a Xamarin-developed project that translated millions of lines of Java to C#.

Java is the underlying code for the Android OS. But one company has changed all that, ripping out most of the Java and replacing it with C#.
That means .NET developers can code in a familiar language and produce apps that leverage C#'s advantages, including speed increases.
It started as a skunkworks project for Xamarin. Xamarin's claim to fame is Mono, an open-source framework allowing Android and iOS apps to be built using C# running on top of Java. Now, with what the company calls the XobotOS Research Project, the Java layer has been removed via a "machine translation of Android from Java to C#," according to a blog post from Xamarin CTO Miguel de Icaza.

Building XobotOS involved converting more than a million lines of Java code into C#, de Icaza wrote. A tool called Sharpen was used to help in the translation, and the project resulted in an improved version of Sharpen, de Icaza says. Most of Androids layouts and controls, de Icaza says, have been converted, and to demonstrate, the post includes a Java-free screenshot of  XobotOS running on a Linux desktop.
In terms of speed improvements, the blog includes a bar chart of a benchmark from a simple binary tree implementation in Java and C#. The chart shows a huge increase in performance between the two languages.
Xamarin has made XobotOS available on github. de Icaza says that XobotOS won't be "a focus" going forward, as the company wants to put its efforts toward its core products, Mono for Android and MonoTouch.
One other possible benefit of using XobotOS for Android development is that it would eliminate the kind of potential legal entanglements that Google finds itself in with Oracle, the patent-holder for Java. Replacing Java with C# would, of course, inoculate developers from the clutches of Oracle's lawyers.

0 comments:

how to use conditions and string formatting in Eval statement in ASP.Net

5:36:00 am 0 Comments

Abstract: Here Al-Salman Rahman has explained how to use conditions and string formatting in Eval statement in ASP.Net 
There are many occasions when you want to have some conditions and also string formatting with Eval, it would be nice to do it in the ASPX page itself but many developers don’t know the syntax and hence I decided to write on this topic. In this article I will explain you how to use string formatting and conditions in the Eval statement of ASP.Net.

Conditions using Eval
Consider a case where I have an old database with old city names hence I need to replace “Bombay” with “Mumbai”, so here’s what I need to do.
<asp:Label ID="Label1" runat="server" Text='<%# Eval("City").ToString() == "Bombay" ? "Mumbai": Eval("City") %>'></asp:Label>

Another is a case where I want to append the Salutation or title as prefix to the names based on gender of the person
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Gender").ToString() == "Male" ? "Mr." + Eval("Name") : "Ms." + Eval("Name") %>'></asp:Label>

We can also control the Visible and Enabled property of a control using Eval in the following way
<asp:Label ID="Label1" runat="server" Text= "Is Available" Visible = '<%# (bool)Eval("IsOnline") %>'></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" Enabled = '<%# (bool)Eval("IsOnline") %>' />
 
String formatting using Eval
You can also use Eval for formatting strings in following way
Below I am appending Dr. as prefix to the name of all Doctors
<asp:Label ID="Label1" runat="server" Text= '<%# Eval("DoctorName", "Dr.{0}") %>'></asp:Label>

You can also use Eval to build URLs for Hyperlinks in following way
<asp:HyperLink ID="HyperLink1" runat="server" Text = "Download" NavigateUrl = '<%# Eval("DocumentId", "~/Downloads.aspx?DocumentId={0}") %>'></asp:HyperLink>
 
That’s it from me in this article. If there’s anything that left out and you want that to be added kindly let me know.

0 comments:

Useful SQL Script – Filling Countries table

4:25:00 am 0 Comments


The following script will insert Countries in a Countries lookup table.
The script is assuming SQL server where the ID is an Identity column.
The Table Countries has two columns (“ID” (identity) and “Country” (varchar))
=======================

INSERT INTO COUNTRIES VALUES('Afghanistan');
INSERT INTO COUNTRIES VALUES('Albania');
INSERT INTO COUNTRIES VALUES('Algeria');
INSERT INTO COUNTRIES VALUES('American Samoa');
INSERT INTO COUNTRIES VALUES('Andorra');
INSERT INTO COUNTRIES VALUES('Angola');
INSERT INTO COUNTRIES VALUES('Anguilla');
INSERT INTO COUNTRIES VALUES('Antarctica');
INSERT INTO COUNTRIES VALUES('Antigua and Barbuda');
INSERT INTO COUNTRIES VALUES('Argentina');
INSERT INTO COUNTRIES VALUES('Armenia');
INSERT INTO COUNTRIES VALUES('Aruba');
INSERT INTO COUNTRIES VALUES('ustralia');
INSERT INTO COUNTRIES VALUES('Austria');
INSERT INTO COUNTRIES VALUES('Azerbaijan');
INSERT INTO COUNTRIES VALUES('Bahamas');
INSERT INTO COUNTRIES VALUES('Bahrain');
INSERT INTO COUNTRIES VALUES('Bangladesh');
INSERT INTO COUNTRIES VALUES('Barbados');
INSERT INTO COUNTRIES VALUES('Belarus ');
INSERT INTO COUNTRIES VALUES('Belgium ');
INSERT INTO COUNTRIES VALUES('Belize');
INSERT INTO COUNTRIES VALUES('Benin');
INSERT INTO COUNTRIES VALUES('Bermuda');
INSERT INTO COUNTRIES VALUES('Bhutan');
INSERT INTO COUNTRIES VALUES('Bolivia');
INSERT INTO COUNTRIES VALUES('Bosnia and Herzegowina');
INSERT INTO COUNTRIES VALUES('Botswana');
INSERT INTO COUNTRIES VALUES('Bouvet Island');
INSERT INTO COUNTRIES VALUES('Brazil');
INSERT INTO COUNTRIES VALUES('British Indian Ocean');
INSERT INTO COUNTRIES VALUES('Brunei Darussalam');
INSERT INTO COUNTRIES VALUES('Bulgaria');
INSERT INTO COUNTRIES VALUES('Burkina Faso ');
INSERT INTO COUNTRIES VALUES('Burundi');
INSERT INTO COUNTRIES VALUES('Cambodia ');
INSERT INTO COUNTRIES VALUES('Cameroon ');
INSERT INTO COUNTRIES VALUES('anada');
INSERT INTO COUNTRIES VALUES('Cape Verde');
INSERT INTO COUNTRIES VALUES('Cayman Islands');
INSERT INTO COUNTRIES VALUES('Central African Republic');
INSERT INTO COUNTRIES VALUES('Chad');
INSERT INTO COUNTRIES VALUES('Chile');
INSERT INTO COUNTRIES VALUES('China');
INSERT INTO COUNTRIES VALUES('Christmas Island');
INSERT INTO COUNTRIES VALUES('Cocos (Keeling) Islands');
INSERT INTO COUNTRIES VALUES('Colombia');
INSERT INTO COUNTRIES VALUES('Comoros');
INSERT INTO COUNTRIES VALUES('Congo (Democratic Republic of the)');
INSERT INTO COUNTRIES VALUES('Congo (Republic of the)');
INSERT INTO COUNTRIES VALUES('Cook islands');
INSERT INTO COUNTRIES VALUES('Costa Rica');
INSERT INTO COUNTRIES VALUES('Cote dIvoire (Ivory Coast)');
INSERT INTO COUNTRIES VALUES('Croatia');
INSERT INTO COUNTRIES VALUES('Cuba');
INSERT INTO COUNTRIES VALUES('Curaco');
INSERT INTO COUNTRIES VALUES('Cyprus');
INSERT INTO COUNTRIES VALUES('Cyprus (Turkish Republic of Northern)');
INSERT INTO COUNTRIES VALUES('Czech Republic');
INSERT INTO COUNTRIES VALUES('Denmark');
INSERT INTO COUNTRIES VALUES('Djibouti ');
INSERT INTO COUNTRIES VALUES('Dominica');
INSERT INTO COUNTRIES VALUES('Dominican Republic');
INSERT INTO COUNTRIES VALUES('East Timor');
INSERT INTO COUNTRIES VALUES('Ecuador');
INSERT INTO COUNTRIES VALUES('Egypt');
INSERT INTO COUNTRIES VALUES('El Salvador');
INSERT INTO COUNTRIES VALUES('Equatorial Guinea');
INSERT INTO COUNTRIES VALUES('Eritrea');
INSERT INTO COUNTRIES VALUES('Estonia');
INSERT INTO COUNTRIES VALUES('Ethiopia');
INSERT INTO COUNTRIES VALUES('Falkland Islands');
INSERT INTO COUNTRIES VALUES('Faroe Islands');
INSERT INTO COUNTRIES VALUES('Fiji');
INSERT INTO COUNTRIES VALUES('Finland');
INSERT INTO COUNTRIES VALUES('France');
INSERT INTO COUNTRIES VALUES('France, Metropolitan');
INSERT INTO COUNTRIES VALUES('French Guiana ');
INSERT INTO COUNTRIES VALUES('French Polynesia');
INSERT INTO COUNTRIES VALUES('French Southern Territories');
INSERT INTO COUNTRIES VALUES('Gabon');
INSERT INTO COUNTRIES VALUES('Gambia');
INSERT INTO COUNTRIES VALUES('Georgia');
INSERT INTO COUNTRIES VALUES('Germany ');
INSERT INTO COUNTRIES VALUES('Ghana');
INSERT INTO COUNTRIES VALUES('Gibraltar');
INSERT INTO COUNTRIES VALUES('Greece');
INSERT INTO COUNTRIES VALUES('Greenland');
INSERT INTO COUNTRIES VALUES('Grenada');
INSERT INTO COUNTRIES VALUES('Guadeloupe');
INSERT INTO COUNTRIES VALUES('Guam');
INSERT INTO COUNTRIES VALUES('Guatemala');
INSERT INTO COUNTRIES VALUES('Guinea');
INSERT INTO COUNTRIES VALUES('Guinea-Bissau');
INSERT INTO COUNTRIES VALUES('Guyana');
INSERT INTO COUNTRIES VALUES('Haiti');
INSERT INTO COUNTRIES VALUES('Heard and Mc Donald Islands');
INSERT INTO COUNTRIES VALUES('Honduras');
INSERT INTO COUNTRIES VALUES('Hong Kong');
INSERT INTO COUNTRIES VALUES('Hungary');
INSERT INTO COUNTRIES VALUES('Iceland');
INSERT INTO COUNTRIES VALUES('India');
INSERT INTO COUNTRIES VALUES('Indonesia');
INSERT INTO COUNTRIES VALUES('Iran');
INSERT INTO COUNTRIES VALUES('Iraq ');
INSERT INTO COUNTRIES VALUES('Ireland');
INSERT INTO COUNTRIES VALUES('Israel');
INSERT INTO COUNTRIES VALUES('Italy');
INSERT INTO COUNTRIES VALUES('Jamaica');
INSERT INTO COUNTRIES VALUES('Japan');
INSERT INTO COUNTRIES VALUES('Jordan');
INSERT INTO COUNTRIES VALUES('Kazakhstan');
INSERT INTO COUNTRIES VALUES('Kenya');
INSERT INTO COUNTRIES VALUES('Kiribati ');
INSERT INTO COUNTRIES VALUES('Korea, Republic of (south)');
INSERT INTO COUNTRIES VALUES('Kosovo');
INSERT INTO COUNTRIES VALUES('Kuwait');
INSERT INTO COUNTRIES VALUES('Kyrgyzstan');
INSERT INTO COUNTRIES VALUES('Laos (Lao Peoples Democratic Republic)');
INSERT INTO COUNTRIES VALUES('Latvia');
INSERT INTO COUNTRIES VALUES('Lebanon');
INSERT INTO COUNTRIES VALUES('Lesotho');
INSERT INTO COUNTRIES VALUES('Liberia');
INSERT INTO COUNTRIES VALUES('Libyan Arab Jamahiriya');
INSERT INTO COUNTRIES VALUES('Liechtenstein');
INSERT INTO COUNTRIES VALUES('Lithuania');
INSERT INTO COUNTRIES VALUES('Luxembourg');
INSERT INTO COUNTRIES VALUES('Macau');
INSERT INTO COUNTRIES VALUES('Macedonia');
INSERT INTO COUNTRIES VALUES('Madagascar');
INSERT INTO COUNTRIES VALUES('Malawi');
INSERT INTO COUNTRIES VALUES('Malaysia');
INSERT INTO COUNTRIES VALUES('Maldives');
INSERT INTO COUNTRIES VALUES('Mali');
INSERT INTO COUNTRIES VALUES('Malta');
INSERT INTO COUNTRIES VALUES('Marshall Islands');
INSERT INTO COUNTRIES VALUES('Martinique ');
INSERT INTO COUNTRIES VALUES('Mauritania');
INSERT INTO COUNTRIES VALUES('Mauritius');
INSERT INTO COUNTRIES VALUES('Mayotte');
INSERT INTO COUNTRIES VALUES('Mexico');
INSERT INTO COUNTRIES VALUES('Micronesia');
INSERT INTO COUNTRIES VALUES('Moldova');
INSERT INTO COUNTRIES VALUES('Monaco');
INSERT INTO COUNTRIES VALUES('Mongolia');
INSERT INTO COUNTRIES VALUES('Montenegro');
INSERT INTO COUNTRIES VALUES('Montserrat');
INSERT INTO COUNTRIES VALUES('Morocco');
INSERT INTO COUNTRIES VALUES('Mozambique');
INSERT INTO COUNTRIES VALUES('Myanmar');
INSERT INTO COUNTRIES VALUES('Namibia');
INSERT INTO COUNTRIES VALUES('Nauru');
INSERT INTO COUNTRIES VALUES('Nepal');
INSERT INTO COUNTRIES VALUES('Netherlands');
INSERT INTO COUNTRIES VALUES('Netherlands Antilles');
INSERT INTO COUNTRIES VALUES('New Caledonia');
INSERT INTO COUNTRIES VALUES('New Zealand');
INSERT INTO COUNTRIES VALUES('Nicaragua');
INSERT INTO COUNTRIES VALUES('Niger');
INSERT INTO COUNTRIES VALUES('Nigeria');
INSERT INTO COUNTRIES VALUES('Niue');
INSERT INTO COUNTRIES VALUES('Norfolk Island');
INSERT INTO COUNTRIES VALUES('Northern Mariana Islands');
INSERT INTO COUNTRIES VALUES('Norway');
INSERT INTO COUNTRIES VALUES('Oman');
INSERT INTO COUNTRIES VALUES('Pakistan');
INSERT INTO COUNTRIES VALUES('Palau');
INSERT INTO COUNTRIES VALUES('Palestine');
INSERT INTO COUNTRIES VALUES('Panama');
INSERT INTO COUNTRIES VALUES('Papua New Guinea');
INSERT INTO COUNTRIES VALUES('Paraguay ');
INSERT INTO COUNTRIES VALUES('Peru');
INSERT INTO COUNTRIES VALUES('Philippines');
INSERT INTO COUNTRIES VALUES('Pitcairn');
INSERT INTO COUNTRIES VALUES('Poland');
INSERT INTO COUNTRIES VALUES('Portugal');
INSERT INTO COUNTRIES VALUES('Puerto Rico');
INSERT INTO COUNTRIES VALUES('Qatar');
INSERT INTO COUNTRIES VALUES('Reunion');
INSERT INTO COUNTRIES VALUES('Romania');
INSERT INTO COUNTRIES VALUES('Russian Federation');
INSERT INTO COUNTRIES VALUES('Rwanda');
INSERT INTO COUNTRIES VALUES('Saint Helena (UK)');
INSERT INTO COUNTRIES VALUES('Saint Kitts and Nevis');
INSERT INTO COUNTRIES VALUES('Saint Lucia');
INSERT INTO COUNTRIES VALUES('Saint Maarten');
INSERT INTO COUNTRIES VALUES('Saint Pierre and Miquelon (FR)');
INSERT INTO COUNTRIES VALUES('Saint Thomas');
INSERT INTO COUNTRIES VALUES('Saint Vincent and the Grenadines');
INSERT INTO COUNTRIES VALUES('Samoa');
INSERT INTO COUNTRIES VALUES('San Marino');
INSERT INTO COUNTRIES VALUES('Sao Tome and Principe');
INSERT INTO COUNTRIES VALUES('Saudi Arabia');
INSERT INTO COUNTRIES VALUES('Senegal');
INSERT INTO COUNTRIES VALUES('Serbia');
INSERT INTO COUNTRIES VALUES('Serbia + Montenegro (old)');
INSERT INTO COUNTRIES VALUES('Seychelles');
INSERT INTO COUNTRIES VALUES('Sierra Leone');
INSERT INTO COUNTRIES VALUES('Singapore');
INSERT INTO COUNTRIES VALUES('Slovakia');
INSERT INTO COUNTRIES VALUES('Slovenia');
INSERT INTO COUNTRIES VALUES('Solomon Islands');
INSERT INTO COUNTRIES VALUES('Somalia');
INSERT INTO COUNTRIES VALUES('South Africa');
INSERT INTO COUNTRIES VALUES('South Georgia and the South Sandwich Islands');
INSERT INTO COUNTRIES VALUES('Spain');
INSERT INTO COUNTRIES VALUES('Sri Lanka');
INSERT INTO COUNTRIES VALUES('Sudan');
INSERT INTO COUNTRIES VALUES('Suricountry');
INSERT INTO COUNTRIES VALUES('Svalbard and Jan Mayen Islands');
INSERT INTO COUNTRIES VALUES('Swaziland');
INSERT INTO COUNTRIES VALUES('Sweden');
INSERT INTO COUNTRIES VALUES('Switzerland');
INSERT INTO COUNTRIES VALUES('Syrian Arab Republic');
INSERT INTO COUNTRIES VALUES('Taiwan');
INSERT INTO COUNTRIES VALUES('Tajikistan');
INSERT INTO COUNTRIES VALUES('Tanzania');
INSERT INTO COUNTRIES VALUES('Thailand');
INSERT INTO COUNTRIES VALUES('Timor-Leste');
INSERT INTO COUNTRIES VALUES('Togo');
INSERT INTO COUNTRIES VALUES('Tokelau');
INSERT INTO COUNTRIES VALUES('Tonga');
INSERT INTO COUNTRIES VALUES('Trinidad and Tobago');
INSERT INTO COUNTRIES VALUES('Tunisia');
INSERT INTO COUNTRIES VALUES('Turkey');
INSERT INTO COUNTRIES VALUES('Turkmenistan');
INSERT INTO COUNTRIES VALUES('Turks and Caicos Islands');
INSERT INTO COUNTRIES VALUES('Tuvalu');
INSERT INTO COUNTRIES VALUES('Uganda');
INSERT INTO COUNTRIES VALUES('Ukraine');
INSERT INTO COUNTRIES VALUES('United Arab Emirates');
INSERT INTO COUNTRIES VALUES('United Kingdom');
INSERT INTO COUNTRIES VALUES('United States of America');
INSERT INTO COUNTRIES VALUES('Uruguay');
INSERT INTO COUNTRIES VALUES('Uzbekistan');
INSERT INTO COUNTRIES VALUES('Vanuatu');
INSERT INTO COUNTRIES VALUES('Vatican City State');
INSERT INTO COUNTRIES VALUES('Venezuela');
INSERT INTO COUNTRIES VALUES('Vietnam');
INSERT INTO COUNTRIES VALUES('Virgin Islands (British)');
INSERT INTO COUNTRIES VALUES('Virgin Islands (U.S.)');
INSERT INTO COUNTRIES VALUES('Wallis and Futuna Islands');
INSERT INTO COUNTRIES VALUES('Western Sahara');
INSERT INTO COUNTRIES VALUES('Yemen');
INSERT INTO COUNTRIES VALUES('Zaire');
INSERT INTO COUNTRIES VALUES('Zambia');
INSERT INTO COUNTRIES VALUES('Zimbabwe');

0 comments:

Cross page posting Submit Form Server.Transfer methods ASP.NET

2:37:00 am 0 Comments

Cross page posting in ASP.NET

To transer data using cross page posting
we need to use FindControl Method
we can write code like this




First of all we need to set the PostBackUrl property of the Button we are gonna use for postback, to the page where we need to redirect, in our case it's Default2.aspx

to retrieve the value of a textbox from previous page in Default2.aspx page
we need to use FindControl method to find the textbox control of previous page

TextBox txtName = (TextBox)PreviousPage.FindControl("txtUserName"));

lblName.text = txtName.Text.ToString();


Submit Form Method to post data and retrieve on another page in ASP.NET

To start with simplest method we can write code like this

<form id="form1" method="post" 
action="Default2.aspx">
Data <input type="text" 
name="Data" size="20"><br>

<input id="Submit1" type="submit" 
value="submit" />
</form>

And to retrieve it on the posted page

lblValue.Text = Request.Form["Data"];


asp.net does not support post method with runat="Server" attribute,
for this we will have to use javascript

<form id="Form1" method="post"
runat="server">
<asp:TextBox ID="txtData" runat="server">
</asp:TextBox>
</form>

<form name="FormSubmit" action="Default2.aspx"
method="post">
<input id="Submit1" type="submit"
value="submit"
onclick="CopyTextToHiddenField()" />
<input name="Hidden1" type="hidden" />
</form>

Ass this JavaScript in the Head section of page to be posted

<script language="javascript">
function CopyTextToHiddenField()
{
var textbox1Value = document.getElementById
("<%=TextBox1.ClientID%>").value;

document.forms[1].document.getElementById
("Hidden1").value = textbox1Value;
}
</script>

To retrieve the value of hidden field
in Default2.aspx page

lblData.Text = Request.Form["Hidden1"];



Server.Transfer Method in ASP.NET

Server.Transfer method sends (transfers) all the state information (all application/session variables and all items in the request collections) created in one ASPX page to a second ASPX page.

you can't use Server.Transfer to send the user to an external site
The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.

For example, if your Default.aspx has a TextBox control called TextBox1 and you transferred to Default2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").

protected void Button1_Click1
(object sender, EventArgs e)
{
Server.Transfer("Default2.aspx", true);
}

Now in Default2.aspx page_load event
use the below code to get the value of TextBox1

Response.Write(Request.Form["TextBox1"]);

0 comments:

Ajax Cascading DropDownList With Database Example in GridView

2:36:00 am 0 Comments

There are several cases when you have two or three dropdowns in gridview and want second one (and third one) to be populated based on selection of first and second dropdownlist.

In this example i've implemented Ajax cascading drop down list in EditItemTemaplete of GridView for updation of records in grid by fetching data from database to populate dropdowns,I've also implemented ajax auto complete extender textbox in it to edit name field


<%@ Page Language="C#" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

Here is explanation why you need to turn it off ?
in order for the values to be submitted, EventValidation needs to be disabled for the page. EventValidation ensures that the values in each control match the values that were present when the page was rendered, but since these drop downs are populating on the client side, this is never true.

3. If you are getting Error method 500 or 12031 than read this to resolve this error

4. Webservice must have the webmethod with following signature and exact parameters
[WebMethod]
public CascadingDropDownNameValue[] GetColorsForModel(
string knownCategoryValues,
string category)

You can change the method name but return type must be CascadingDropDownNameValue[] with knownCategoryValues,category as parameters

First of all add a new webservice and name it CascadingDropDown.asmx
In code behind of this asmx file write following code
Add these namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
using System.Collections.Specialized;

/// <summary>
/// Summary description for CascadingDropDown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CascadingDropDown : System.Web.Services.WebService
{
//Create global Connection string
string strConnection = ConfigurationManager.ConnectionStrings
["dbConnectionString"].ConnectionString;

public CascadingDropDown () {

//Uncomment the following line if using designed components 
//InitializeComponent(); 
}
/// <summary>
/// WebMethod to populate country Dropdown
/// </summary>
/// <param name="knownCategoryValues"></param>
/// <param name="category"></param>
/// <returns>countrynames</returns>
[WebMethod]
public CascadingDropDownNameValue[] GetCountries
(string knownCategoryValues, string category)
{
//Create sql connection and sql command
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Select * from Country";

//Create dataadapter and fill the dataset
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();

//create list and add items in it 
//by looping through dataset table
List<CascadingDropDownNameValue> countryNames
= new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string countryID = dRow["CountryID"].ToString();
string countryName = dRow["CountryName"].ToString();
countryNames.Add(new CascadingDropDownNameValue
(countryName, countryID));
}
return countryNames.ToArray();


}

[WebMethod]
public CascadingDropDownNameValue[] GetCities
(string knownCategoryValues, string category)
{
int countryID;
//this stringdictionary contains has table with key value
//pair of cooountry and countryID
StringDictionary countryValues =
AjaxControlToolkit.CascadingDropDown.
ParseKnownCategoryValuesString(knownCategoryValues);
countryID = Convert.ToInt32(countryValues["Country"]);

SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@CountryID", countryID);
cmd.CommandText =
"Select * from City where CountryID = @CountryID";

SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();
List<CascadingDropDownNameValue> cityNames =
new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string cityID = dRow["CityID"].ToString();
string cityName = dRow["CityName"].ToString();
cityNames.Add(new CascadingDropDownNameValue
(cityName, cityID));
}
return cityNames.ToArray();
}

}


Now in html source of aspx page I've put two dropdowns in EditItemTemaplate of gridview
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>


Here TargetControlID is id of dropdown on which cascading dropdown is to be implemented ,Service path is path to webservice and ServiceMethod is method to fetch the data from databse and populate dropdown

You also need to add reference to webservive in script manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>


The complete html source is like this
<%@ Page Language="C#" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnRowUpdating="GridView1_RowUpdating">

<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Eval("ID") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Bind("ID") %>'>
</asp:Label>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name"
SortExpression="Name">
<ItemTemplate>
<asp:Label ID = "lblName" runat="server"
Text='<%#Eval("Name") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%#Bind("Name") %>' >
</asp:TextBox>
<ajaxToolkit:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="txtName"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12" />
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Country"
SortExpression="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%#Eval("Country") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList>
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City"
SortExpression="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%#Eval("City") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server"
OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown2"
runat="server"
Category="City"
TargetControlID="ddlCity"
ParentControlID="ddlCountry"
PromptText="-Select City-"
LoadingText="Loading Cities.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCities">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
SelectCommand="SELECT [ID], [Name], [City],[Country]
FROM [Location]"
UpdateCommand="Update Location set [Name] = @Name,
[City] = @City,[Country] = @Country
where ID = @ID">
<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="ID" />
<asp:Parameter Name="Country"/>
<asp:Parameter Name="City"/>
</UpdateParameters>
</asp:SqlDataSource>

</div>
</form> 
</body>
</html>


Finally write this code in code behind of aspx page to update record
protected void GridView1_RowUpdating
(object sender, GridViewUpdateEventArgs e)
{
//Find dropdown to get selected Item text  
DropDownList ddlGridCountry = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCountry");
string strCountry =
ddlGridCountry.SelectedItem.Text.ToString();

DropDownList ddlGridCity = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCity");
string strCity =
ddlGridCity.SelectedItem.Text.ToString();

SqlDataSource1.UpdateParameters.Clear();
SqlDataSource1.UpdateParameters.Add
("Country", strCountry);
SqlDataSource1.UpdateParameters.Add("City", strCity);
}


Hope this helps

I wrote similar article in case you don't use ajax , than u can go through this


Download the sample code attached

0 comments:

Insert Update Edit Delete record in GridView

2:35:00 am 0 Comments

In this example i am going to describe how to Insert record or edit or delete record in GridView using SqlDataSource.

For inserting record, i've put textboxes in footer row of GridView using ItemTemplate and FooterTemaplete.


Go to design view of aspx page and drag a GridView control from toolbox, click on smart tag of GridView and choose new datasource
Select Database and click Ok
 
In next screen, Enter your SqlServer name , username and password and pick Database name from the dropdown , Test the connection
 
 
 In next screen, select the table name and fields , Click on Advance tab and check Generate Insert,Edit and Delete statements checkbox , alternatively you can specify your custom sql statements 
 
 
Click on ok to finish 
Check Enable Editing , enable deleting checkbox in gridView smart tag 
Now go to html source of page and define DatakeyNames field in gridview source
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
</asp:GridView>
Remove the boundFields and put ItemTemplate and EditItemTemplate and labels and textboxs respectively, complete html source of page should look like this
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
<Columns>
    <asp:CommandField ShowDeleteButton="True" 
                      ShowEditButton="True" />
    <asp:TemplateField HeaderText="ID" SortExpression="ID">
    <ItemTemplate>
    <asp:Label ID="lblID" runat="server" 
                          Text='<%#Eval("ID") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:Button ID="btnInsert" runat="server" 
                Text="Insert" CommandName="Add" />
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="FirstName" 
                       SortExpression="FirstName">
    <ItemTemplate>
    <asp:Label ID="lblFirstName" runat="server" 
               Text='<%#Eval("FirstName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtFirstName" runat="server" 
                 Text='<%#Bind("FirstName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="LastName" 
                       SortExpression="LastName">
    <ItemTemplate>
    <asp:Label ID="lblLastName" runat="server" 
               Text='<%#Eval("LastName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLastName" runat="server" 
                 Text='<%#Bind("LastName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Department" 
                       SortExpression="Department">
    <ItemTemplate>
    <asp:Label ID="lblDepartment" runat="server" 
               Text='<%#Eval("Department") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtDepartmentName" runat="server" 
                 Text='<%#Bind("Department") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtDept" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Location" 
                       SortExpression="Location">
    <ItemTemplate>
    <asp:Label ID="lblLocation" runat="server" 
               Text='<%#Eval("Location") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLocation" runat="server" 
                 Text='<%#Bind("Location") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLoc" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DBConString%>"
DeleteCommand="DELETE FROM [Employees] WHERE [ID] = @ID" 
InsertCommand="INSERT INTO [Employees] ([FirstName], 
[LastName],[Department], [Location]) 
VALUES (@FirstName, @LastName, @Department, @Location)"
SelectCommand="SELECT [ID], [FirstName], [LastName], 
[Department], [Location] FROM [Employees]"
UpdateCommand="UPDATE [Employees] SET 
[FirstName] = @FirstName, [LastName] = @LastName, 
[Department] = @Department, [Location] = @Location 
WHERE [ID] = @ID" OnInserted="SqlDataSource1_Inserted">

<DeleteParameters>
    <asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
    <asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
<asp:Label ID="lblMessage" runat="server" 
           Font-Bold="True"></asp:Label><br />
</div>
</form>
Write this code in RowCommand Event of GridView in codebehind
C# code Behind
protected void GridView1_RowCommand
(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Add")
  {
   string strFirstName = ((TextBox)
   GridView1.FooterRow.FindControl("txtFname")).Text;

   string strLastName = 
   ((TextBox)GridView1.FooterRow.FindControl
                         ("txtLname")).Text;

   string strDepartment = 
   ((TextBox)GridView1.FooterRow.FindControl
                            ("txtDept")).Text;
   string strLocation = ((TextBox)GridView1.FooterRow.
                          FindControl("txtLoc")).Text;
   //SqlDataSource1.InsertParameters.Clear();
   //SqlDataSource1.InsertParameters.Add
                       //("FirstName", strFirstName);
   //SqlDataSource1.InsertParameters.Add
                          //("LastName", strLastName);
   //SqlDataSource1.InsertParameters.Add
                         //("Department", strDepartment);
   //SqlDataSource1.InsertParameters.Add
                              //("Location", strLocation);

  SqlDataSource1.InsertParameters["FirstName"].DefaultValue 
                                             = strFirstName;
  SqlDataSource1.InsertParameters["LastName"].DefaultValue 
                                             = strLastName;
  SqlDataSource1.InsertParameters["Department"].DefaultValue 
                                             = strDepartment;
  SqlDataSource1.InsertParameters["Location"].DefaultValue
                                            = strLocation;
  SqlDataSource1.Insert();
  }
}

VB.NET Code Behind

Protected Sub GridView1_RowCommand(ByVal sender As Object, 
                       ByVal e As GridViewCommandEventArgs)
        If e.CommandName = "Add" Then
            Dim strFirstName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtFname"), TextBox).Text()

            Dim strLastName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLname"), TextBox).Text()

            Dim strDepartment As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtDept"), TextBox).Text()
            Dim strLocation As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLoc"), TextBox).Text()

            'SqlDataSource1.InsertParameters.Clear();
            'SqlDataSource1.InsertParameters.Add
            '("FirstName", strFirstName);
            'SqlDataSource1.InsertParameters.Add
            '("LastName", strLastName);
            'SqlDataSource1.InsertParameters.Add
            '("Department", strDepartment);
            'SqlDataSource1.InsertParameters.Add
            '("Location", strLocation);

            SqlDataSource1.InsertParameters("FirstName").
            DefaultValue = strFirstName
            SqlDataSource1.InsertParameters("LastName").
            DefaultValue = strLastName
            SqlDataSource1.InsertParameters("Department").
            DefaultValue = strDepartment
            SqlDataSource1.InsertParameters("Location").
            DefaultValue = strLocation
            SqlDataSource1.Insert()
        End If
    End Sub


Download the sample code attached

0 comments:

GridView XML Edit Delete Insert Update

2:34:00 am 2 Comments

GridView XML Edit Delete Insert Update.

In this post i'm explaining how to Edit Delete Insert and update XML file data in GridView using C# and VB.Net in Asp.Net.

GridView Xml Edit Delete Insert Update
Read GridView XMLDataSource Example to know how to use XMLDataSource in GridView with XSLT schema.

For this example i have created a XML file with three fields Firstname,LastName and Location and XML file looks like mentioned below.


01<!--?xml version="1.0" standalone="yes"?-->
02<employees>
03  <details>
04    <firstname>Amit</firstname>
05    <lastname>Jain</lastname>
06    <location>Mumbai</location>
07  </details>
08  <details>
09    <firstname>User</firstname>
10    <lastname>3</lastname>
11    <location>Noida</location>
12  </details>
13  <details>
14    <firstname>User</firstname>
15    <lastname>4</lastname>
16    <location>Bangalore</location>
17  </details>
18</employees>

I have placed one gridview on aspx page and three textbox in editItemTemplate of gridview for editing, one button and three textbox in Footer Template for Inserting new records in XML file.

HTML SOURCE OF PAGE
<asp:GridView ID="gridviewXMLInsertEditDelete" runat="server" 
AutoGenerateColumns="False" ShowFooter="True" 
onRowCancelingEdit="gridviewXMLInsertEditDelete_RowCancelingEdit" 
onRowDeleting="gridviewXMLInsertEditDelete_RowDeleting" 
onRowEditing="gridviewXMLInsertEditDelete_RowEditing" 
onRowUpdating="gridviewXMLInsertEditDelete_RowUpdating" 
onRowCommand="gridviewXMLInsertEditDelete_RowCommand">
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFname" runat="server" 
           Text='<%#Eval("FirstName") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" 
             Text='<%#Bind("FirstName") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnInsert" runat="server" 
            Text="Insert" CommandName="InsertXMLData"/>
<asp:TextBox ID="txtFirstNameInsert" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLname" runat="server" 
           Text='<%#Eval("LastName") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" 
             Text='<%#Bind("LastName") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastNameInsert" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" 
           Text='<%#Eval("Location") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" 
             Text='<%#Bind("Location") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLocationInsert" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

c# CODE
01protected void Page_Load(object sender, EventArgs e)
02    {
03        if (!Page.IsPostBack)
04            BindGridView();
05    }
06    protected void BindGridView()
07    {
08        DataSet dsGridViewXMLEditDeleteUpdate = new DataSet();
09        dsGridViewXMLEditDeleteUpdate.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"));
10        gridviewXMLInsertEditDelete.DataSource = dsGridViewXMLEditDeleteUpdate;
11        gridviewXMLInsertEditDelete.DataBind();
12        gridviewXMLInsertEditDelete.ShowFooter = true;
13    }
14 
15    protected void gridviewXMLInsertEditDelete_RowDeleting(object sender, GridViewDeleteEventArgs e)
16    {
17        BindGridView();
18        DataSet dsGridViewXMLDelete = (DataSet)gridviewXMLInsertEditDelete.DataSource;
19        dsGridViewXMLDelete.Tables[0].Rows[gridviewXMLInsertEditDelete.Rows[e.RowIndex].DataItemIndex].Delete();
20        dsGridViewXMLDelete.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
21        BindGridView();
22 
23    }
24    protected void gridviewXMLInsertEditDelete_RowEditing(object sender, GridViewEditEventArgs e)
25    {
26        gridviewXMLInsertEditDelete.ShowFooter = false;
27        gridviewXMLInsertEditDelete.EditIndex = e.NewEditIndex;
28        BindGridView();
29    }
30    protected void gridviewXMLInsertEditDelete_RowUpdating(object sender, GridViewUpdateEventArgs e)
31    {
32        int index = gridviewXMLInsertEditDelete.Rows[e.RowIndex].DataItemIndex;
33        string firstName = ((TextBox)gridviewXMLInsertEditDelete.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
34        string lastName = ((TextBox)gridviewXMLInsertEditDelete.Rows[e.RowIndex].FindControl("txtLastName")).Text;
35        string location = ((TextBox)gridviewXMLInsertEditDelete.Rows[e.RowIndex].FindControl("txtLocation")).Text;
36        gridviewXMLInsertEditDelete.EditIndex = -1;
37        BindGridView();
38        DataSet dsUpdateXMLFile = (DataSet)gridviewXMLInsertEditDelete.DataSource;
39        dsUpdateXMLFile.Tables[0].Rows[index]["FirstName"] = firstName;
40        dsUpdateXMLFile.Tables[0].Rows[index]["LastName"] = lastName;
41        dsUpdateXMLFile.Tables[0].Rows[index]["Location"] = location;
42        dsUpdateXMLFile.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
43        BindGridView();
44 
45    }
46    protected void gridviewXMLInsertEditDelete_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
47    {
48        gridviewXMLInsertEditDelete.EditIndex = -1;
49        BindGridView();
50    }
51 
52    protected void gridviewXMLInsertEditDelete_RowCommand(object sender, GridViewCommandEventArgs e)
53    {
54 
55        if(e.CommandName == "InsertXMLData")
56        {
57        string firstname = ((TextBox)gridviewXMLInsertEditDelete.FooterRow.FindControl("txtFirstNameInsert")).Text;
58        string lastname = ((TextBox)gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLastNameInsert")).Text;
59        string location = ((TextBox)gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLocationInsert")).Text;
60        BindGridView();
61        DataSet dsXMLInsert = (DataSet)gridviewXMLInsertEditDelete.DataSource;
62        DataRow drInsert = dsXMLInsert.Tables[0].NewRow();
63        drInsert["FirstName"] = firstname;
64        drInsert["LastName"] = lastname;
65        drInsert["Location"] = location;
66        dsXMLInsert.Tables[0].Rows.Add(drInsert);
67        dsXMLInsert.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
68        BindGridView();
69        }
70    }

VB.NET CODE
01Protected Sub Page_Load(sender As Object, e As EventArgs)
02 If Not Page.IsPostBack Then
03  BindGridView()
04 End If
05End Sub
06Protected Sub BindGridView()
07 Dim dsGridViewXMLEditDeleteUpdate As New DataSet()
08 dsGridViewXMLEditDeleteUpdate.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"))
09 gridviewXMLInsertEditDelete.DataSource = dsGridViewXMLEditDeleteUpdate
10 gridviewXMLInsertEditDelete.DataBind()
11 gridviewXMLInsertEditDelete.ShowFooter = True
12End Sub
13 
14Protected Sub gridviewXMLInsertEditDelete_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
15 BindGridView()
16 Dim dsGridViewXMLDelete As DataSet = DirectCast(gridviewXMLInsertEditDelete.DataSource, DataSet)
17 dsGridViewXMLDelete.Tables(0).Rows(gridviewXMLInsertEditDelete.Rows(e.RowIndex).DataItemIndex).Delete()
18 dsGridViewXMLDelete.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
19 BindGridView()
20 
21End Sub
22Protected Sub gridviewXMLInsertEditDelete_RowEditing(sender As Object, e As GridViewEditEventArgs)
23 gridviewXMLInsertEditDelete.ShowFooter = False
24 gridviewXMLInsertEditDelete.EditIndex = e.NewEditIndex
25 BindGridView()
26End Sub
27Protected Sub gridviewXMLInsertEditDelete_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
28 Dim index As Integer = gridviewXMLInsertEditDelete.Rows(e.RowIndex).DataItemIndex
29 Dim firstName As String = DirectCast(gridviewXMLInsertEditDelete.Rows(e.RowIndex).FindControl("txtFirstName"), TextBox).Text
30 Dim lastName As String = DirectCast(gridviewXMLInsertEditDelete.Rows(e.RowIndex).FindControl("txtLastName"), TextBox).Text
31 Dim location As String = DirectCast(gridviewXMLInsertEditDelete.Rows(e.RowIndex).FindControl("txtLocation"), TextBox).Text
32 gridviewXMLInsertEditDelete.EditIndex = -1
33 BindGridView()
34 Dim dsUpdateXMLFile As DataSet = DirectCast(gridviewXMLInsertEditDelete.DataSource, DataSet)
35 dsUpdateXMLFile.Tables(0).Rows(index)("FirstName") = firstName
36 dsUpdateXMLFile.Tables(0).Rows(index)("LastName") = lastName
37 dsUpdateXMLFile.Tables(0).Rows(index)("Location") = location
38 dsUpdateXMLFile.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
39 BindGridView()
40 
41End Sub
42Protected Sub gridviewXMLInsertEditDelete_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
43 gridviewXMLInsertEditDelete.EditIndex = -1
44 BindGridView()
45End Sub
46 
47Protected Sub gridviewXMLInsertEditDelete_RowCommand(sender As Object, e As GridViewCommandEventArgs)
48 
49 If e.CommandName = "InsertXMLData" Then
50  Dim firstname As String = DirectCast(gridviewXMLInsertEditDelete.FooterRow.FindControl("txtFirstNameInsert"), TextBox).Text
51  Dim lastname As String = DirectCast(gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLastNameInsert"), TextBox).Text
52  Dim location As String = DirectCast(gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLocationInsert"), TextBox).Text
53  BindGridView()
54  Dim dsXMLInsert As DataSet = DirectCast(gridviewXMLInsertEditDelete.DataSource, DataSet)
55  Dim drInsert As DataRow = dsXMLInsert.Tables(0).NewRow()
56  drInsert("FirstName") = firstname
57  drInsert("LastName") = lastname
58  drInsert("Location") = location
59  dsXMLInsert.Tables(0).Rows.Add(drInsert)
60  dsXMLInsert.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
61  BindGridView()
62 End If
63End Sub

Build and run the application.

Download Sample Code

2 comments: