C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




GridView Tips and Tricks using ASP.NET 2.0


Posted Date: 30 Apr 2008    Resource Type: Code Snippets    Category: ASP.NET GridView

Posted By: Vivs       Member Level: Gold
Rating:     Points: 25



Tip 1: Add, Update, Delete Records in a Gridview using SqlDataSource
By default, the GridView control doesn’t have support for inserting new records. However you can use the built-in edit or delete functionality of the GridView control. Let us explore how to insert new records and Update and Delete existing records in Gridview. Just copy and paste the code in your project. We will be using the ‘Categories’ table in the ‘Northwind’ database.
GridView.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Grid View Add Update Delete</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True" OnRowCommand="GridView1_RowCommand">
<Columns>

<asp:CommandField ShowDeleteButton="True" ShowEditButton="True"/>
<asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("CategoryID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="CategoryNameTextBox" Runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DescriptionTextBox" Runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:templatefield>
<footertemplate>
<asp:linkbutton id="btnNew" runat="server" commandname="New" text="New" />
</footertemplate>
</asp:templatefield>

</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial Catalog=Northwind;Integrated Security=True"
DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID" InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]"
UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID">
<DeleteParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="CategoryName" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="CategoryID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="CategoryName" Type="String" />
<asp:Parameter Name="Description" Type="String" />
</InsertParameters>
</asp:SqlDataSource>

</div>
</form>
</body>
</html>
GridView.aspx.cs
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
try
{
if (e.CommandName.Equals("New"))
{
LinkButton btnNew = e.CommandSource as LinkButton;
GridViewRow row = btnNew.NamingContainer as GridViewRow;
if (row == null)
{
return;
}
TextBox txtCatName = row.FindControl("CategoryNameTextBox") as TextBox;
TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;
SqlCommand cmd = new SqlCommand(
"INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)",
conn);
cmd.Parameters.AddWithValue("CategoryName", txtCatName.Text);
cmd.Parameters.AddWithValue("Description",txtDescription.Text);
conn.Open();
if (cmd.ExecuteNonQuery() == 1)
{
GridView1.DataBind();
}
}
}
catch (Exception ex)
{

}
finally
{
conn.Close();
}
}
Web.config
<connectionStrings>
<addname="NorthwindConnectionString"connectionString="Data Source =.;Integrated Security = SSPI; Initial Catalog=Northwind;"/>

</connectionStrings>




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: How to format values in column of gridview
Previous Resource: How to use javascript to confirm delete from a GridView
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET GridView


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

email fax service

Contact Us    Privacy Policy    Terms Of Use