2

CreateUserWizard Email Verification Or Confirmation In Asp.NET

CreateUserWizard Email Confirmation or verification
CreateUserWizard Email Verification Or Confirmation In Asp.NET.

In this example i am explaining how to create new user using createnewuserwizard with membership provider and sending verification or confirmation link in Email using C# or VB in ASP.NET.

Read Login Page Using Login Control to know how to create login page in asp.net and setup membership provider to use with login control.


For this example i have created one NewUser.aspx page to place createuserwizard on it to create new users or signups.

One EmailVerification.aspx page to open when user clicks on the link in email sent to his emailid at the time of creating new account.

This page will verify,confirm or validate new user account and activate it. when new account is created through wizard, it will be deactivated and user won't be able to login untill he clicks on the link sent to his email id, clicking on the link activates new account.



First of all create a email template which you want to send to users who sign up or create new account onthe site. for this create a text file and write the text mentioned below and name it mail.txt.

Hello <%UserName%>!.

You or someone with your email id signed up at this site, Your new account is almost ready, but before you can login you need to confirm your email id by visitng the link below:
<%VerificationUrl%>

Once you have visited the verification URL, your account will be activated.

If you have any problems or questions, please reply to this email.

Thanks!

Open NewUser.aspx page in design view and palce a CreateUserWizard control on it.

Set DisableCreatedUser property to true to deactivate new accounts untill user activate it by clicking the link sent in email.


Set MailDefinition property as mentioned below for wizard to send cenfirmation emails.

<MailDefinition From="YourGmailID@gmail.com" 
                Subject="Confirmation mail" 
                BodyFileName="~/mail.txt">
</MailDefinition>

HTML source of NewUser.aspx will look like
<form id="form1" runat="server">
<asp:CreateUserWizard ID="CreateUserWizard1" 
                      runat="server" 
                      DisableCreatedUser="True" 
        ContinueDestinationPageUrl="~/Login.aspx" 
        onsendingmail="CreateUserWizard1_SendingMail">
<MailDefinition From="YourGmailID@gmail.com" 
                Subject="Confirmation mail" 
                BodyFileName="~/mail.txt">
</MailDefinition>
<WizardSteps>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
</form>

Write code mentioned below in SendingMail event of CreateUserWizard control in code behind of page.

C# CODE
using System.Net.Mail;
using System.Web.Security;

protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e)
    {
        MembershipUser newUserAccount = Membership.GetUser(CreateUserWizard1.UserName);
        Guid newUserAccountId = (Guid)newUserAccount.ProviderUserKey;
        string domainName = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
        string confirmationPage = "/EmailConfirmation.aspx?ID=" + newUserAccountId.ToString();
        string url = domainName + confirmationPage;
        e.Message.Body = e.Message.Body.Replace("<%VerificationUrl%>", url);
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential("YourGmailUserName@gmail.com", "YourGmailPassword");
        smtp.EnableSsl = true;
        smtp.Send(e.Message);
        e.Cancel = true;
    }

VB.NET CODE
Protected Sub CreateUserWizard1_SendingMail(sender As Object, e As MailMessageEventArgs)
 Dim newUserAccount As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)
 Dim newUserAccountId As Guid = DirectCast(newUserAccount.ProviderUserKey, Guid)
 Dim domainName As String = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath
 Dim confirmationPage As String = "/EmailConfirmation.aspx?ID=" & newUserAccountId.ToString()
 Dim url As String = domainName & confirmationPage
 e.Message.Body = e.Message.Body.Replace("<%VerificationUrl%>", url)
 Dim smtp As New SmtpClient()
 smtp.Host = "smtp.gmail.com"
 smtp.Port = 587
 smtp.UseDefaultCredentials = False
 smtp.Credentials = New System.Net.NetworkCredential("YourGmailUserName@gmail.com", "YourGmailPassword")
 smtp.EnableSsl = True
 smtp.Send(e.Message)
 e.Cancel = True
End Sub

Email sent to new user's email id provided in email section of wizard will look like shown below.
Createuserwizard verification email

To activate user account through EmailConfirmation.aspx page Place a label control on the page and write below mentioned code in Page_Load Event.

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        Guid newUserId = new Guid(Request.QueryString["ID"]);
        MembershipUser newUser = Membership.GetUser(newUserId);
        if (newUser == null)
        {
            lblMessage.Text = "User Account not found";
        }
        else
        {
            newUser.IsApproved = true;
            Membership.UpdateUser(newUser);
            lblMessage.Text = "Account Approved, please  Login to continue";
        }
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim newUserId As New Guid(Request.QueryString("ID"))
 Dim newUser As MembershipUser = Membership.GetUser(newUserId)
 If newUser Is Nothing Then
  lblMessage.Text = "User Account not found"
 Else
  newUser.IsApproved = True
  Membership.UpdateUser(newUser)
  lblMessage.Text = "Account Approved, please  Login to continue"
 End If
End Sub


Build and run the application.

Download Sample Code



1

Login Page Example Using Login Control In Asp.Net

Creating login page in asp.net with login control
Creating Login Page In Asp.Net using Login Control And Membership Provider DataBase ASPNETDB.MDF.


In this post i'm explaining how to create login page in asp.net using Login COntrol and membership provider database ASPNETDB.MDF.

Create a new website and add new web form in the solution, name it Login.aspx,






Place a Login control on this Login.aspx page from toolbox in visual studio.

Assign DestinationPageUrl property of Login control to the page we want to open after login, i m redirecting to Default.aspx page.

HTML SOURCE OF LOGIN.ASPX PAGE
<form id="form1" runat="server">
<asp:Login ID="Login1" runat="server" 
           onloginerror="Login1_LoginError"
           RememberMeSet="True"
           DestinationPageUrl="~/Default.aspx">
</asp:Login>
</form>


Place a LoginStatus and LoginName control on Default.aspx page to display username and logout hyperlink.

HTML SOURCE OF DEFAULT.ASPX PAGE
<form id="form1" runat="server">
 <div>
 <asp:LoginStatus ID="LoginStatus1" runat="server" />
 Welcome
 <asp:LoginName ID="LoginName1" runat="server" />
</div>
</form>


Now we need to configure our website or application to use membership provider database to authenticate user login credentials.

For this Click on website menu of visual studio and select ASP.NET Configuration.

Asp.Net membership provider website configuration

Click on Security Tab and click on Use the security Setup Wizard to configure security step by step link.

Security configuration

Click next on welcome screen And Select From the internet option in next screen.

access method

Click next and reach to step 5 to create new user, enter username and password and other informations and click on create user.

create new user

In next screen Select Anonymous User radion button and then select deny permission, click on add this rule to dent anonymous access to site.

deny anonymous access

CLick on finish to complete asp.net membership provider configuration.

This will autometically add ASPNETDB.MDF database in App_Data Folder.

Build and run the application, login with the credentials used in creating new user in configuration.


2

Set Session TimeOut In Asp.Net Using WebConfig IIS

Set Session Timeout in Asp.Net using web.config and IIS
Set Or Manage Session TimeOut In Asp.Net Using Web.Config and IIS

In this post i'm explaining how to set or increase session timeout value in web.config or IIS in Asp.Net.

Read Detecting Session Timeout and Redirect to Login Page in ASP.NET to know how to detect Session TimeOut.

1. Set session timeout in IIS.

Open IIS manager by typing inetmgr in Start > run in windows.

Right click on websites > Select Properties.





Go to ASP.NET tab, Click on Edit Configuration.

Increase Session TimeOut In asp.Net web.config

Click on State Management Tab, Set Session TimeOut value (In Minutes).


2. Set Session TimeOut in Web.Config

We can set session timeout in SessionState section of web.config file as mentioned below, timeout value is in minutes.

<system.web>
    <sessionState mode="InProc" cookieless="false" timeout="15">
    </sessionState>
</system.web>

3. Set session timeout in Global.asax

void Session_Start(object sender, EventArgs e)
{
  // Code that runs when a new session is started
  Session.Timeout = 15;
}


0

Remove Delete Duplicate Rows/Records From DataTable

Remove Duplicate Rows Records from datatable

Remove/Delete Duplicate Rows/Records From Datatable.

Here i'm describing how to remove or delete duplicate rows or duplicate records from datatable using C# or VB.NET in Asp.Net.

My table in database contains duplicate records as shown in image and i want to remove those duplicate records temporaryly efore displaying them in gridview.

For this purpose i'm filling records in DataTable and deleting duplicates.

I have placed one gridview on the page and populating it from DataTable in Page_Load event in code behind.

There are two ways to remove duplicates from datatable.



Method 1:

In this method we create a DataView on DataTable and pass the column names to check for duplicates as array in ToTable method of DataView.

C# CODE
DataView dView = new DataView(dtRemoveDuplicate);
        string[] arrColumns = { "Id", "Name", "Location" };
        dtRemoveDuplicate = dView.ToTable(true, arrColumns);

VB.NET CODE
Dim dView As New DataView(dtRemoveDuplicate)
Dim arrColumns As String() = {"Id", "Name", "Location"}
dtRemoveDuplicate = dView.ToTable(True, arrColumns)

Method 2 :

Create a method which takes datatable and column name to look for duplicates as parameter and returns DataTable after removing duplicate records.

C# CODE
protected DataTable DeleteDuplicateFromDataTable(DataTable dtDuplicate, string columnName)
    {
        Hashtable hashT = new Hashtable();
        ArrayList arrDuplicate = new ArrayList();
        foreach (DataRow row in dtDuplicate.Rows)
        {
            if (hashT.Contains(row[columnName]))
                arrDuplicate.Add(row);
            else
                hashT.Add(row[columnName], string.Empty);
        }
        foreach (DataRow row in arrDuplicate)
            dtDuplicate.Rows.Remove(row);

        return dtDuplicate;
    }

Write this code in Page_Load event of page

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        string strConnection = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        SqlConnection con = new SqlConnection();
        con.ConnectionString = strConnection;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT * FROM Details";
        cmd.Connection = con;
        SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
        DataTable dtRemoveDuplicate = new DataTable();
        dAdapter.Fill(dtRemoveDuplicate);
        dtRemoveDuplicate = DeleteDuplicateFromDataTable(dtRemoveDuplicate, "Id");
        GridView1.DataSource = dtRemoveDuplicate;
        GridView1.DataBind();
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
 Dim con As New SqlConnection()
 con.ConnectionString = strConnection
 Dim cmd As New SqlCommand()
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "SELECT * FROM Details"
 cmd.Connection = con
 Dim dAdapter As New SqlDataAdapter(cmd)
 Dim dtRemoveDuplicate As New DataTable()
 dAdapter.Fill(dtRemoveDuplicate)
 dtRemoveDuplicate = DeleteDuplicateFromDataTable(dtRemoveDuplicate, "Id")
 GridView1.DataSource = dtRemoveDuplicate
 GridView1.DataBind()
End Sub
Protected Function DeleteDuplicateFromDataTable(dtDuplicate As DataTable, columnName As String) As DataTable
 Dim hashT As New Hashtable()
 Dim arrDuplicate As New ArrayList()
 For Each row As DataRow In dtDuplicate.Rows
  If hashT.Contains(row(columnName)) Then
   arrDuplicate.Add(row)
  Else
   hashT.Add(row(columnName), String.Empty)
  End If
 Next
 For Each row As DataRow In arrDuplicate
  dtDuplicate.Rows.Remove(row)
 Next

 Return dtDuplicate
End Function

Delete Duplicate Records from datatable
And result will be as shown in the image.

All duplicate records have been removed from DataTable.






Download Sample Code


0

DropDownList In DetailsView EditItemTemplate

DropDownList In EditItemTemplate of DetailsView

DropDownList And RadioButtonList In EditItemTemplate Of DetailsView In Asp.Net.

In This Example i'm going to explain how to put dropdownlist and radiobutton control in EditItemTemplate of DetailsView and Edit or Update Records of DetailsView in asp.net.

For this i have used SqlDataSource To fetch records from database and populate and update detailsview.





HTML SOURCE OF ASPX PAGE
<asp:DetailsView ID="DetailsView2" runat="server"
                 AllowPaging="True" DataKeyNames="ID"
                 AutoGenerateRows="False"
                 DataSourceID="SqlDataSource2" Height="50px"
                 Width="125px"
                 onDataBound="DetailsView2_DataBound"
                 onItemUpdating="DetailsView2_ItemUpdating">
<Fields>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label ID="lblGender" runat="server" Text='<%#Eval("Sex") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="rbGender" runat="server">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%#Eval("Status") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server">
<asp:ListItem>Single</asp:ListItem>
<asp:ListItem>Married</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
</div>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Sex], [Status] FROM [Details]"
UpdateCommand="UPDATE Details SET Name = @Name, Sex = @Sex,
MaritalStatus = @Stauts WHERE (ID = @ID)">
<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="Sex" />
<asp:Parameter Name="Stauts" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>

Now to pouplate value from database in selected index of dropdown and then set the new selected value in sqldatasource parameter write below mentioned code in DataBound and ItemUpdating Event of DetailsView respectively.

C# CODE
protected void DetailsView2_DataBound(object sender, EventArgs e)
    {
        if (((DetailsView)sender).CurrentMode == DetailsViewMode.Edit)
        {
                DataRowView row = (DataRowView)((DetailsView)sender).DataItem;
                RadioButtonList rblGender = (RadioButtonList)((DetailsView)sender).FindControl("rbGender");
                DropDownList ddlStatus = (DropDownList)((DetailsView)sender).FindControl("ddlStatus");
                rblGender.SelectedValue = row[2].ToString();
                ddlStatus.SelectedValue = row[3].ToString();
        }
    }
    protected void DetailsView2_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        RadioButtonList rblGender = (RadioButtonList)((DetailsView)sender).FindControl("rbGender");
        DropDownList ddlStatus = (DropDownList)((DetailsView)sender).FindControl("ddlStatus");
        SqlDataSource2.UpdateParameters["Sex"].DefaultValue = rblGender.SelectedValue;
        SqlDataSource2.UpdateParameters["Stauts"].DefaultValue = ddlStatus.SelectedValue;
    }

VB.NET CODE
Protected Sub DetailsView2_DataBound(sender As Object, e As EventArgs)
 If DirectCast(sender, DetailsView).CurrentMode = DetailsViewMode.Edit Then
  Dim row As DataRowView = DirectCast(DirectCast(sender, DetailsView).DataItem, DataRowView)
  Dim rblGender As RadioButtonList = DirectCast(DirectCast(sender, DetailsView).FindControl("rbGender"), RadioButtonList)
  Dim ddlStatus As DropDownList = DirectCast(DirectCast(sender, DetailsView).FindControl("ddlStatus"), DropDownList)
  rblGender.SelectedValue = row(2).ToString()
  ddlStatus.SelectedValue = row(3).ToString()
 End If
End Sub
Protected Sub DetailsView2_ItemUpdating(sender As Object, e As DetailsViewUpdateEventArgs)
 Dim rblGender As RadioButtonList = DirectCast(DirectCast(sender, DetailsView).FindControl("rbGender"), RadioButtonList)
 Dim ddlStatus As DropDownList = DirectCast(DirectCast(sender, DetailsView).FindControl("ddlStatus"), DropDownList)
 SqlDataSource2.UpdateParameters("Sex").DefaultValue = rblGender.SelectedValue
 SqlDataSource2.UpdateParameters("Stauts").DefaultValue = ddlStatus.SelectedValue
End Sub

Build and run the application.

Download Sample Code


0

A Potentially Dangerous Request.Form Value Was Detected From Client

Potentially dengerous requestForm error

A potentially dangerous Request.Form value was detected from the client.

This A potentially dangerous Request.Form value was detected from the client error occurs when user enter any script tag <> like or any html <> tag like etc in taxtbox.

Reason for this is asp.net prevent any attempt to compromise the security of application by script injection like cross site scriptiong etc through textbox.

To resolve this issue we can do following things.



1. Set validateRequest property to false in page directive.

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

2.You can set ValidateRequest property to false in web.config if you want to turn validateRequest off for the whole application
<configuration>
  <configuration>
    <system.web>
      <pages validateRequest="false" />
    </system.web>
</configuration>

3. If you don't want to set validateRequest to false then use methods like regular expression or replace() to check for any special character or script tag entry in text box

<asp:textbox id="TextBox2" runat="server"
             onblur="this.value = this.value.replace(/&lt;\/?[^>]+>/gi, '');">
</asp:textbox>

hope this helps.


0

Write Modify Web.Config Programmatically At Run Time

Write web.config programmatically
Write or Modify Web.Config ConnectionString Programmatically At Run Time In Asp.Net

In this post I'm going to explain how to write or modify CnnectionStrings and AppSettings programmatically at run time in Web.Config file in Asp.Net.

To write or modify web.config programmatically we need to use ebConfigurationManager Class in System.Web.Configuration namespace.



We can add write or modify any section of web.config programmatically, here i m describing how to modify and write connectionStrings and AppSettings section of Web.Config file.

For this first of all add this namespace in code behind of page.

using System.Web.Configuration;

I have put two textbox on the page to display on Page Load and write new or modify existing connectionString in web.config file on Button Click Event.

HTML SOURCE OF PAGE
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtKey" runat="server">
</asp:TextBox>
<asp:TextBox ID="txtConnectionString" runat="server">
</asp:TextBox>
<asp:Button ID="btnWrite" runat="server" 
            onclick="btnWrite_Click" 
            Text="Modify/Write" />
</div>
</form>

Write below mentioned code in code behind of page to show existing connectionString in web.config on page Load.

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
          txtConnectionString.Text = ConfigurationManager.ConnectionStrings[0].ConnectionString;
            
        }
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then

  txtConnectionString.Text = ConfigurationManager.ConnectionStrings(0).ConnectionString
 End If
End Sub

To modify name of existing connection string in web.config programmatically write below mentioned code in Click Event of Button.

C# CODE
protected void btnWrite_Click(object sender, EventArgs e)
    {
        Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
        connectionConfiguration.ConnectionStrings.ConnectionStrings["test"].Name = txtKey.Text;
        connectionConfiguration.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("connectionStrings");
    }

To modify value of existing connection string in web.config programmatically write below mentioned code in Click Event of Button.

C# CODE
protected void btnWrite_Click(object sender, EventArgs e)
    {
        Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
        connectionConfiguration.ConnectionStrings.ConnectionStrings["test"].ConnectionString = txtConnectionString.Text;
connectionConfiguration.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");

VB.NET CODE
Protected Sub btnWrite_Click(sender As Object, e As EventArgs)
 Dim connectionConfiguration As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
 connectionConfiguration.ConnectionStrings.ConnectionStrings("test").Name = txtKey.Text
 connectionConfiguration.ConnectionStrings.ConnectionStrings("test").ConnectionString = txtConnectionString.Text
 connectionConfiguration.Save(ConfigurationSaveMode.Modified)
 ConfigurationManager.RefreshSection("connectionStrings")
End Sub

To add or write new name and value of connection string in web.config at run time write below mentioned code

C# CODE
protected void btnWrite_Click(object sender, EventArgs e)
    {
        Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
        
        ConnectionStringSettings csAddNewConString = new ConnectionStringSettings(txtKey.Text,txtConnectionString.Text ,"System.Data.SqlClient");
        
 ConnectionStringsSection csNewConSection = connectionConfiguration.ConnectionStrings;
        
 csNewConSection.ConnectionStrings.Add(csAddNewConString);
        
        connectionConfiguration.Save(ConfigurationSaveMode.Modified);

        ConfigurationManager.RefreshSection("connectionStrings");
    }

VB.NET CODE
Protected Sub btnWrite_Click(sender As Object, e As EventArgs)
 Dim connectionConfiguration As Configuration = WebConfigurationManager.OpenWebConfiguration("~")

 Dim csAddNewConString As New ConnectionStringSettings(txtKey.Text, txtConnectionString.Text, "System.Data.SqlClient")

 Dim csNewConSection As ConnectionStringsSection = connectionConfiguration.ConnectionStrings

 csNewConSection.ConnectionStrings.Add(csAddNewConString)

 connectionConfiguration.Save(ConfigurationSaveMode.Modified)

 ConfigurationManager.RefreshSection("connectionStrings")
End Sub


To write or add new key and value of connectionstring in AppSettings Section of web.config we can write code as mentioned below.

C# CODE
protected void btnWrite_Click(object sender, EventArgs e)
    {
        Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
        
        connectionConfiguration.AppSettings.Settings.Add("writeAppSettingsString", txtConnectionString.Text);
        
        connectionConfiguration.Save(ConfigurationSaveMode.Modified);
        
        ConfigurationManager.RefreshSection("connectionStrings");
    }

VB.NET CODE
Protected Sub btnWrite_Click(sender As Object, e As EventArgs)
 Dim connectionConfiguration As Configuration = WebConfigurationManager.OpenWebConfiguration("~")

 connectionConfiguration.AppSettings.Settings.Add("writeAppSettingsString", txtConnectionString.Text)

 connectionConfiguration.Save(ConfigurationSaveMode.Modified)

 ConfigurationManager.RefreshSection("connectionStrings")
End Sub

To remove any existing connection string in AppSettings we can use Remove() method

connectionConfiguration.AppSettings.Settings.Remove("writeAppSettingsString");

Hope this helps.


1

GridView XML Edit Delete Insert Update

GridView Xml Edit Delete Insert Update
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.

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.




  
Amit Jain Mumbai
User 3 Noida
User 4 Bangalore

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
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            BindGridView();
    }
    protected void BindGridView()
    {
        DataSet dsGridViewXMLEditDeleteUpdate = new DataSet();
        dsGridViewXMLEditDeleteUpdate.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        gridviewXMLInsertEditDelete.DataSource = dsGridViewXMLEditDeleteUpdate;
        gridviewXMLInsertEditDelete.DataBind();
        gridviewXMLInsertEditDelete.ShowFooter = true;
    }

    protected void gridviewXMLInsertEditDelete_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        BindGridView();
        DataSet dsGridViewXMLDelete = (DataSet)gridviewXMLInsertEditDelete.DataSource;
        dsGridViewXMLDelete.Tables[0].Rows[gridviewXMLInsertEditDelete.Rows[e.RowIndex].DataItemIndex].Delete();
        dsGridViewXMLDelete.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();

    }
    protected void gridviewXMLInsertEditDelete_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gridviewXMLInsertEditDelete.ShowFooter = false;
        gridviewXMLInsertEditDelete.EditIndex = e.NewEditIndex;
        BindGridView();
    }
    protected void gridviewXMLInsertEditDelete_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int index = gridviewXMLInsertEditDelete.Rows[e.RowIndex].DataItemIndex;
        string firstName = ((TextBox)gridviewXMLInsertEditDelete.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
        string lastName = ((TextBox)gridviewXMLInsertEditDelete.Rows[e.RowIndex].FindControl("txtLastName")).Text;
        string location = ((TextBox)gridviewXMLInsertEditDelete.Rows[e.RowIndex].FindControl("txtLocation")).Text;
        gridviewXMLInsertEditDelete.EditIndex = -1;
        BindGridView();
        DataSet dsUpdateXMLFile = (DataSet)gridviewXMLInsertEditDelete.DataSource;
        dsUpdateXMLFile.Tables[0].Rows[index]["FirstName"] = firstName;
        dsUpdateXMLFile.Tables[0].Rows[index]["LastName"] = lastName;
        dsUpdateXMLFile.Tables[0].Rows[index]["Location"] = location;
        dsUpdateXMLFile.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();
        
    }
    protected void gridviewXMLInsertEditDelete_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gridviewXMLInsertEditDelete.EditIndex = -1;
        BindGridView();
    }
    
    protected void gridviewXMLInsertEditDelete_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        
        if(e.CommandName == "InsertXMLData")
        {
        string firstname = ((TextBox)gridviewXMLInsertEditDelete.FooterRow.FindControl("txtFirstNameInsert")).Text;
        string lastname = ((TextBox)gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLastNameInsert")).Text;
        string location = ((TextBox)gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLocationInsert")).Text;
        BindGridView();
        DataSet dsXMLInsert = (DataSet)gridviewXMLInsertEditDelete.DataSource;
        DataRow drInsert = dsXMLInsert.Tables[0].NewRow();
        drInsert["FirstName"] = firstname;
        drInsert["LastName"] = lastname;
        drInsert["Location"] = location;
        dsXMLInsert.Tables[0].Rows.Add(drInsert);
        dsXMLInsert.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();
        }
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not Page.IsPostBack Then
  BindGridView()
 End If
End Sub
Protected Sub BindGridView()
 Dim dsGridViewXMLEditDeleteUpdate As New DataSet()
 dsGridViewXMLEditDeleteUpdate.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"))
 gridviewXMLInsertEditDelete.DataSource = dsGridViewXMLEditDeleteUpdate
 gridviewXMLInsertEditDelete.DataBind()
 gridviewXMLInsertEditDelete.ShowFooter = True
End Sub

Protected Sub gridviewXMLInsertEditDelete_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
 BindGridView()
 Dim dsGridViewXMLDelete As DataSet = DirectCast(gridviewXMLInsertEditDelete.DataSource, DataSet)
 dsGridViewXMLDelete.Tables(0).Rows(gridviewXMLInsertEditDelete.Rows(e.RowIndex).DataItemIndex).Delete()
 dsGridViewXMLDelete.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
 BindGridView()

End Sub
Protected Sub gridviewXMLInsertEditDelete_RowEditing(sender As Object, e As GridViewEditEventArgs)
 gridviewXMLInsertEditDelete.ShowFooter = False
 gridviewXMLInsertEditDelete.EditIndex = e.NewEditIndex
 BindGridView()
End Sub
Protected Sub gridviewXMLInsertEditDelete_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
 Dim index As Integer = gridviewXMLInsertEditDelete.Rows(e.RowIndex).DataItemIndex
 Dim firstName As String = DirectCast(gridviewXMLInsertEditDelete.Rows(e.RowIndex).FindControl("txtFirstName"), TextBox).Text
 Dim lastName As String = DirectCast(gridviewXMLInsertEditDelete.Rows(e.RowIndex).FindControl("txtLastName"), TextBox).Text
 Dim location As String = DirectCast(gridviewXMLInsertEditDelete.Rows(e.RowIndex).FindControl("txtLocation"), TextBox).Text
 gridviewXMLInsertEditDelete.EditIndex = -1
 BindGridView()
 Dim dsUpdateXMLFile As DataSet = DirectCast(gridviewXMLInsertEditDelete.DataSource, DataSet)
 dsUpdateXMLFile.Tables(0).Rows(index)("FirstName") = firstName
 dsUpdateXMLFile.Tables(0).Rows(index)("LastName") = lastName
 dsUpdateXMLFile.Tables(0).Rows(index)("Location") = location
 dsUpdateXMLFile.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
 BindGridView()

End Sub
Protected Sub gridviewXMLInsertEditDelete_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
 gridviewXMLInsertEditDelete.EditIndex = -1
 BindGridView()
End Sub

Protected Sub gridviewXMLInsertEditDelete_RowCommand(sender As Object, e As GridViewCommandEventArgs)

 If e.CommandName = "InsertXMLData" Then
  Dim firstname As String = DirectCast(gridviewXMLInsertEditDelete.FooterRow.FindControl("txtFirstNameInsert"), TextBox).Text
  Dim lastname As String = DirectCast(gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLastNameInsert"), TextBox).Text
  Dim location As String = DirectCast(gridviewXMLInsertEditDelete.FooterRow.FindControl("txtLocationInsert"), TextBox).Text
  BindGridView()
  Dim dsXMLInsert As DataSet = DirectCast(gridviewXMLInsertEditDelete.DataSource, DataSet)
  Dim drInsert As DataRow = dsXMLInsert.Tables(0).NewRow()
  drInsert("FirstName") = firstname
  drInsert("LastName") = lastname
  drInsert("Location") = location
  dsXMLInsert.Tables(0).Rows.Add(drInsert)
  dsXMLInsert.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
  BindGridView()
 End If
End Sub

Build and run the application.

Download Sample Code


Popular Posts

Find More Articles