Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
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 :
Page Views : 7682
Downloads : 255
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DetailsViewWithoutSQLDataSource.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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();
    }

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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);
}

 [Top] Rate this article
 
 About the author
 
Raj Kumar

Raj Kumar is a Microsoft MVP and Senior Software Engineer with lots of hands on experience using ASP.NET 2.0/3.5, AJAX, MVC, C#, Visual Basic .NET, SQL Server 2005/2008, Oracle, WPF, WCF, XAML and Silverlight. He has over 6 years of IT experience working most on Microsoft technologies. He holds Master's degree in Computer Science. When he is not writing code, he likes to write articles and play cricket.

Reach him at raj2511984@gmail.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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
DetailsView by AVJEET SINGH On December 9, 2010
thnx for the help
Reply | Email | Modify 
Re: DetailsView by Raj On December 15, 2010
No problem
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.