Yasserzaid’s Weblog

December 17, 2008

Insert New Record with Gridview

Filed under: ASP.Net — yasserzaid @ 8:38 pm

Try this example:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=107

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" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
 
<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">
    <title>Grid View Add Update Delete</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <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>

 
Tip 2: Paging and Sorting a GridView without Refreshing a Page
If you have created a GridView and have bound it to a data source control, you can avoid postback during sorting and paging by setting  ‘EnableSortingAndPagingCallbacks’ property of the GridView to True.
Just remember that when you set the ‘EnableSortingAndPagingCallbacks’ property to true, you cannot use Template Fields in the GridView.
 
Tip 3: Pop-up a Confirmation box before Deleting a row in GridView
Add a template field and drop a button in it, using which the user will delete the record. In the OnClientClick event, call the confirm() function as mentioned below:

<asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="btnDel" runat="server" Text="Delete"
            CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete the record?');" />
      </ItemTemplate>
</asp:TemplateField>

 
Tip 4: Display details of the Row selected in the GridView
Assuming you have a button called ‘Select’ in your GridView with CommandName ‘Select’, to find out the row clicked and display the row’s details, use this code:
C#

private void GridView1_RowCommand(Object sender,
GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int idx = Convert.ToInt32(e.CommandArgument);
            GridViewRow selrow = GridView1.Rows[idx];
            string fstCell  = selrow.Cells[0].Text;
string scndCell = selrow.Cells[1].Text;
// and so on
// Thanks to Mark Rae (MVP) for pointing the typo. Earlier it was Cells[1] and Cells [2]
        }
    }

 
Tip 5: Retrieve Details of the Row being Modified in GridView
C#

void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
    {
        // Retrieve the row being edited.
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];
 
        // Retrieve the value of the first cell
        lblMsg.Text = "Updated record " + row.Cells[1].Text;
    }

 
Tip 6: Retrieve Details of the Row being Deleted in GridView
The ID of the row being deleted must be in the GridView.DataKeyNames collection.
C#

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
        // Query the database and get the values based on the ID
    }

 
Tip 7: Cancelling Update and Delete in a GridView
RowUpdating – Occurs when a row’s Update button is clicked, but before the GridView control updates the row.
RowDeleting – Occurs when a row’s Delete button is clicked, but before the GridView control deletes the row.
C#

protected void gvDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        e.Cancel = true;
    }
void GridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e)
    {
        // Check for a condition and cancel the delete
        // There should be atleast one row left in the GridView
        if (GridView1.Rows.Count <= 1)
        {
            e.Cancel = true;
        }
    }

 
Tip 8: Paging and Sorting in GridView without using Datasource control

C#

<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging"
OnSorting="gridView_Sorting" runat="server" />

and in code behind :-

private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
   string newSortDirection = String.Empty;
   switch (sortDirection)
   {
      case SortDirection.Ascending:
         newSortDirection = "ASC";
         break;
      case SortDirection.Descending:
         newSortDirection = "DESC";
         break;
   }
   return newSortDirection
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
   DataTable dataTable = gridView.DataSource as DataTable;
   if (dataTable != null)
   {
      DataView dataView = new DataView(dataTable);
      dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
      gridView.DataSource = dataView;
      gridView.DataBind();
   }
}

  
Tip 9: Export GridView To Excel


C#

protected void Button1_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.Charset = String.Empty;
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        Response.Write(sw.ToString());
        Response.End();
    }

Good Luck

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.