Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET Controls » Using ASP.NET DetailsView Control without SQLDataSource

Using ASP.NET DetailsView Control without SQLDataSource

This article will show you how to use a DetailsView control without using a SQLDataSource data control.

Author Rank:
Total page views :  2473
Total downloads :  86
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DetailsViewWithoutSQLDataSource.zip
 
Become a Sponsor


This article will show you how to use DetailsView control without using of SQLDataSource data control.

In my previous article DetailsView Rich Data Control we have learned how to use DetailsView using SQLDataSource data control...I got many mails about how to use DetailsView without SQLDataSource. So here we go.....

I m using Northwind database. Here is my connection string:

<connectionStrings> 
                   <add name="ConnectionString" connectionString="Data Source=RAJ-PC\SQLSERVER2005;UID=sa;pwd=wintellect;Initial Catalog=NORTHWND;" providerName="System.Data.SqlClient"/> 
</connectionStrings>

Here is html code for the control

<
asp:DetailsView ID="DetailsView1" runat="server" DataKeyNames="CustomerID"

            CellPadding="6" ForeColor="#333333"  AutoGenerateRows="false"

            GridLines="None" AllowPaging="True" AutoGenerateDeleteButton="True"

            AutoGenerateEditButton="True" AutoGenerateInsertButton="True"

            onitemdeleting="DetailsView1_ItemDeleting"                         

            onpageindexchanging="DetailsView1_PageIndexChanging"

            oniteminserting="DetailsView1_ItemInserting"

            onitemupdating="DetailsView1_ItemUpdating"

            oniteminserted="DetailsView1_ItemInserted"

            onitemupdated="DetailsView1_ItemUpdated"

            onmodechanging="DetailsView1_ModeChanging1">

            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

            <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />

            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

            <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />

            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

            <Fields>

                 <asp:TemplateField HeaderText="CustomerID" Visible="True" InsertVisible="True" >

                            <ItemTemplate>

                                <asp:Label ID="CustomerIDLabel" Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>

                            </ItemTemplate>

                             <EditItemTemplate>

                                                      <asp:TextBox ID="EditCustomerID" runat="server" Text='<%# Bind("CustomerID") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertCustomerIDTextBox" runat="server" Text='<%# Bind("CustomerID") %>' MaxLength="10" /></InsertItemTemplate>

                         </asp:TemplateField>   

                               <asp:TemplateField HeaderText="CompanyName">           

                            <ItemTemplate>

                                                      <asp:Label ID="CompanyNameLabel" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditCompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertCompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                               <asp:TemplateField HeaderText="ContactName">           

                            <ItemTemplate>

                                                      <asp:Label ID="ContactNameLabel" runat="server" Text='<%# Bind("ContactName") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditContactNameTextBox" runat="server" Text='<%# Bind("ContactName") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertContactNameTextBox" runat="server" Text='<%# Bind("ContactName") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                               <asp:TemplateField HeaderText="ContactTitle">           

                            <ItemTemplate>

                                                      <asp:Label ID="ContactTitleLabel" runat="server" Text='<%# Bind("ContactTitle") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditContactTitleTextBox" runat="server" Text='<%# Bind("ContactTitle") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertContactTitleTextBox" runat="server" Text='<%# Bind("ContactTitle") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                               <asp:TemplateField HeaderText="Address">           

                            <ItemTemplate>

                                                      <asp:Label ID="AddressLabel" runat="server" Text='<%# Bind("Address") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditAddressTextBox" runat="server" Text='<%# Bind("Address") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertAddressTextBox" runat="server" Text='<%# Bind("Address") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                               <asp:TemplateField HeaderText="City">           

                            <ItemTemplate>

                                                      <asp:Label ID="CityLabel" runat="server" Text='<%# Bind("City") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditCityTextBox" runat="server" Text='<%# Bind("City") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertCityTextBox" runat="server" Text='<%# Bind("City") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                              <asp:TemplateField HeaderText="Region">           

                            <ItemTemplate>

                                                      <asp:Label ID="RegionLabel" runat="server" Text='<%# Bind("Region") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditRegionTextBox" runat="server" Text='<%# Bind("Region") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertRegionTextBox" runat="server" Text='<%# Bind("Region") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                              <asp:TemplateField HeaderText="PostalCode">           

                            <ItemTemplate>

                                                      <asp:Label ID="PostalCodeLabel" runat="server" Text='<%# Bind("PostalCode") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditPostalCodeTextBox" runat="server" Text='<%# Bind("PostalCode") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertPostalCodeTextBox" runat="server" Text='<%# Bind("PostalCode") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                              <asp:TemplateField HeaderText="Country">             

                            <ItemTemplate>

                                                      <asp:Label ID="CountryLabel" runat="server" Text='<%# Bind("Country") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditCountryTextBox" runat="server" Text='<%# Bind("Country") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertCountryTextBox" runat="server" Text='<%# Bind("Country") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                               <asp:TemplateField HeaderText="Phone">           

                            <ItemTemplate>

                                                      <asp:Label ID="PhoneLabel" runat="server" Text='<%# Bind("Phone") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditPhoneTextBox" runat="server" Text='<%# Bind("Phone") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertPhoneTextBox" runat="server" Text='<%# Bind("Phone") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

                               <asp:TemplateField HeaderText="Fax">           

                            <ItemTemplate>

                                                      <asp:Label ID="FaxLabel" runat="server" Text='<%# Bind("Fax") %>'></asp:Label>

                                                      </ItemTemplate>                                                                             

                            <EditItemTemplate>

                                                      <asp:TextBox ID="EditFaxTextBox" runat="server" Text='<%# Bind("Fax") %>' MaxLength="10" /></EditItemTemplate>

                            <InsertItemTemplate>

                                                      <asp:TextBox ID="InsertFaxTextBox" runat="server" Text='<%# Bind("Fax") %>' MaxLength="10" /></InsertItemTemplate>

                              </asp:TemplateField>  

              

            </Fields>

            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

            <EditRowStyle BackColor="#999999" />

            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

        </asp:DetailsView>

Connection string called here:

string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlCommand cmd = new SqlCommand();
    DataTable dt = new DataTable();
    SqlConnection con;


Page load event.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getCustomers();
        }
    }
    private void getCustomers()
    {
        con = new SqlConnection(str);
        cmd.Connection = con;
        cmd.CommandText = "SELECT * FROM CUSTOMERS";       
        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        ad.Fill(dt);
        DetailsView1.DataSource = dt;
        DetailsView1.DataBind();  
    }

1.jpg

Figure 1.

ItemUpdate event fired.

protectedted void DetailsView1_ItemUpdating(objectDetailsViewUpdateEventArgs e)
    {       
        con = new SqlConnection(str);
        DataKey key = DetailsView1.DataKey;
        TextBox txtCompanyName = (TextBox)DetailsView1.FindControl("EditCompanyNameTextBox");
        TextBox txtContactName = (TextBox)DetailsView1.FindControl("EditContactNameTextBox");
        TextBox txtContactTitle = (TextBox)DetailsView1.FindControl("EditContactTitleTextBox");
        TextBox txtAddress = (TextBox)DetailsView1.FindControl("EditAddressTextBox");
        TextBox txtCity = (TextBox)DetailsView1.FindControl("EditCityTextBox");
        TextBox txtRegion = (TextBox)DetailsView1.FindControl("EditRegionTextBox");>);

      
TextBox txtPostalCode = (TextBox)DetailsView1.FindControl("EditPostalCodeTextBox");
        TextBox txtCountry = (TextBox)DetailsView1.FindControl("EditCountryTextBox");
        TextBox txtPhone = (TextBox)DetailsView1.FindControl("EditPhoneTextBox");
        TextBox txtFax = (TextBox)DetailsView1.FindControl("EditFaxTextBox");
        cmd.Connection = con;
        cmd.CommandText = "UPDATE CUSTOMERS SET CompanyName ='" + txtCompanyName.Text + "',ContactName ='" + txtContactName.Text + "',ContactTitle ='" + txtContactTitle.Text + "',Address ='" + txtAddress.Text + "',City ='" + txtCity.Text + "', Region ='" + txtRegion.Text + "',PostalCode ='" + txtPostalCode.Text + "',Country ='" + txtCountry.Text + "',Phone ='" + txtPhone.Text + "',Fax ='" + txtFax.Text + "'   WHERE CustomerID='" + key.Value.ToString() + "'"ot;;
        con.Open();
        cmd.ExecuteNonQuery();
        MessageLabel.Text = "Record updated successfully";
        getCustomers();
        con.Close();
    }

2.jpg

Figure 2.

ItemInsert event fired.

protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {       
        con = new SqlConnection(str);
        TextBox txtCustomerID = (TextBox)DetailsView1.FindControl("InsertCustomerIDTextBox");
        TextBox txtCompanyName = (TextBox)DetailsView1.FindControl("InsertCompanyNameTextBox");
        TextBox txtContactName = (TextBox)DetailsView1.FindControl("InsertContactNameTextBox");
        TextBox txtContactTitle = (TextBox)DetailsView1.FindControl("InsertContactTitleTextBox");
        TextBox txtAddress = (TextBox)DetailsView1.FindControl("InsertAddressTextBox");
        TextBox txtCity = (TextBox)DetailsView1.FindControl("InsertCityTextBox");
        TextBox txtRegion = (TextBox)DetailsView1.FindControl("InsertRegionTextBox");
        TextBox txtPostalCode = (TextBox)DetailsView1.FindControl("InsertPostalCodeTextBox");
        TextBox txtCountry = (TextBox)DetailsView1.FindControl("InsertCountryTextBox");
        TextBox txtPhone = (TextBox)DetailsView1.FindControl("InsertPhoneTextBox");
        TextBox txtFax = (TextBox)DetailsView1.FindControl("InsertFaxTextBox");
        cmd.Connection = con;
        cmd.CommandText = "INSERT INTO CUSTOMERS(CustomerID, CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax) Values('" + txtCustomerID.Text + "', '" + txtCompanyName.Text + "', '" + txtContactName.Text + "', '" + txtContactTitle.Text + "', '" + txtAddress.Text + "' , '" + txtCity.Text + "', '" + txtRegion.Text + "', '" + txtPostalCode.Text + "', '" + txtCountry.Text + "', '" + txtPhone.Text + "', '" + txtFax.Text + "')";
        con.Open();
        cmd.ExecuteNonQuery();
        MessageLabel.Text = "Record inserted successfully";       
        getCustomers();
        con.Close();
    }

3.jpg

Figure 3.

ItemDelete fired.

protecteded void DetailsView1_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {       
        DataKey key = DetailsView1.DataKey;
        MessageLabel.Text = "The key value is " + key.Value.ToString() + ".";
        con = new SqlConnection(str);
        cmd.Connection = con;
        cmd.CommandText = "DELETE FROM CUSTOMERS WHERE CustomerID='" + key.Value.ToString() + "'";
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        MessageLabel.Text = "Record deleted successfully";
        getCustomers();  
    }

PageIndex changing event used for paging.

protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
    {
        DetailsView1.PageIndex = e.NewPageIndex;
        getCustomers();
    }


Login to add your contents and source code to this article
 Article Extensions
Contents added by Raj Kumar on Nov 03, 2009

protected void DetailsView1_ModeChanging1(object sender, DetailsViewModeEventArgs e)
{
DetailsView1.ChangeMode(e.NewMode);
getCustomers();
if (e.NewMode == DetailsViewMode.Edit)
{
DetailsView1.AllowPaging =
false;
}
else
{
DetailsView1.AllowPaging =
true;
}
}

protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
DetailsView1.ChangeMode(
DetailsViewMode.ReadOnly);
}

protected void DetailsView1_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
DetailsView1.ChangeMode(
DetailsViewMode.ReadOnly);
}

 About the author
 
Raj Kumar
Rajkumar is working as a senior software engineer has over 5 years experience working on ASP.NET, VB.NET, C#, AJAX and other latest technologies. He holds Master's degree in Computer Science. currently enjoying working on WPF, WCF, Silverlight, MVC, XAML.I can be reached on at raj2511984 at yahoo.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DetailsViewWithoutSQLDataSource.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Click Here for 6 Months Free! Powerful ASP.NET Hosting at your Fingertips!
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.