Showing posts with label EditItemTemplate. Show all posts
Showing posts with label EditItemTemplate. Show all posts
0

DropDownList In DetailsView EditItemTemplate

DropDownList And RadioButtonList In EditItemTemplate Of DetailsView to Edit and Update In Asp.Net.

DropDownList In EditItemTemplate of DetailsView
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.

We need to write code in DataBound And ItemUpdating Events of Detailsview to get the selected value in dropdownlist from database when edit or update button is pressed.



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


5

GridView XML Edit Delete Insert Update

GridView XML Edit Delete Insert Update. In this example i'm explaining how to Edit Delete Insert and update XML file data in GridView using C# and VB.Net in Asp.Net.

GridView Xml Edit Delete Insert Update Asp.Net
I have created a XML file with three fields Firstname,LastName and Location.

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="GridView1" runat="server" 
              AutoGenerateColumns="False" ShowFooter="True" 
              onrowcancelingedit="GridView1_RowCancelingEdit" 
              onrowdeleting="GridView1_RowDeleting" 
              onrowediting="GridView1_RowEditing" 
              onrowupdating="GridView1_RowUpdating" 
              onrowcommand="GridView1_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") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%#Bind("FirstName")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btn" runat="server" Text="Insert" CommandName="InsertXMLData"/>
<asp:TextBox ID="txtFirstNameInsert" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLname" runat="server" Text='<%#Eval("LastName") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%#Bind("LastName") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastNameInsert" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" Text='<%#Bind("Location") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLocationInsert" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


c# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            BindGridView();
    }
    protected void BindGridView()
    {
        DataSet dsXML = new DataSet();
        dsXML.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        GridView1.DataSource = dsXML;
        GridView1.DataBind();
        GridView1.ShowFooter = true;
    }

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

    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.ShowFooter = false;
        GridView1.EditIndex = e.NewEditIndex;
        BindGridView();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int index = GridView1.Rows[e.RowIndex].DataItemIndex;
        string firstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
        string lastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
        string location = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLocation")).Text;
        GridView1.EditIndex = -1;
        BindGridView();
        DataSet dsUpdate = (DataSet)GridView1.DataSource;
        dsUpdate.Tables[0].Rows[index]["FirstName"] = firstName;
        dsUpdate.Tables[0].Rows[index]["LastName"] = lastName;
        dsUpdate.Tables[0].Rows[index]["Location"] = location;
        dsUpdate.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();
        
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGridView();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        
        if(e.CommandName == "InsertXMLData")
        {
        string firstname = ((TextBox)GridView1.FooterRow.FindControl("txtFirstNameInsert")).Text;
        string lastname = ((TextBox)GridView1.FooterRow.FindControl("txtLastNameInsert")).Text;
        string location = ((TextBox)GridView1.FooterRow.FindControl("txtLocationInsert")).Text;
        BindGridView();
        DataSet dsInsert = (DataSet)GridView1.DataSource;
        DataRow drInsert = dsInsert.Tables[0].NewRow();
        drInsert["FirstName"] = firstname;
        drInsert["LastName"] = lastname;
        drInsert["Location"] = location;
        dsInsert.Tables[0].Rows.Add(drInsert);
        dsInsert.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();
        }
    }

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

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

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

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

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

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

Build and run the application.

Download Sample Code


3

GridView EditItemTemplate Example

In this post i am listing some GridView EditItemTemplate examples in Asp.Net 2.0,3.5,4.0 with C# Csharp and VB.NET.


autocomplete textbox in GridView

Example of Ajax Autocomplete Extender TextBox in EditItemTemplate of GridView.







Insert Edit Delete In GridView

Insert Update Edit and Delete Records In GridView using ItemTemplate and EditItemTemplate.





Search in GridView

Search records in GridView footer using footer template and ItemTemplate and highlight results using Ajax





Checkbox In GridView To Edit Or Update

Implementing Check All CheckBox in ItemTemplate of GridView to perform Bulk Editing or Deleting









Hope This Helps


.

20

Check All Checkbox In GridView To Bulk Edit Update ASP.NET

This example explains how to use Check All Checkbox In GridView To Bulk Edit Or Update in ASP.NET with C# and VB.NET. I have put a checkBox in header Template of gridview which on checking will check all rows in gridview using server side code to implement CheckAll CheckBox functionality.

CheckAll CheckBox In GridView to Edit and Update


Html SOURCE OF GRIDVIEW
<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="false" 
              CellPadding="2" ForeColor="#333333" 
              GridLines="Both" 
              DataKeyNames="ID" 
              OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelectAll_CheckedChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID" 
                SortExpression="ID"/>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" 
             Text='<%# Bind("Name") %>' ForeColor="Blue" 
             BorderStyle="none" BorderWidth="0px" 
             ReadOnly="true" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" 
             Text='<%# Bind("Location") %>' 
             ForeColor="Blue" BorderStyle="none" 
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]" 
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)" 
UpdateCommand="UPDATE [Details] SET [Name] = @Name, 
               [Location] = @Location WHERE [ID] = @ID">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>

<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="Location" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>

<asp:Button ID="btnUpdate" runat="server" 
            OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server" 
            OnClick="btnDelete_Click" 
            Text="Delete" />

C# CODE
protected void chkSelectAll_CheckedChanged
                               (object sender, EventArgs e)
{
 CheckBox chkAll = 
    (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
 if (chkAll.Checked == true)
 {
   foreach (GridViewRow gvRow in GridView1.Rows)
   {
    CheckBox chkSel = 
         (CheckBox)gvRow.FindControl("chkSelect");
    chkSel.Checked = true;
    TextBox txtname = (TextBox)gvRow.FindControl("txtName");
    TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
    txtname.ReadOnly = false;
    txtlocation.ReadOnly = false;
    txtname.ForeColor = System.Drawing.Color.Black;
    txtlocation.ForeColor = System.Drawing.Color.Black;
   }
 }
 else
 {
  foreach (GridViewRow gvRow in GridView1.Rows)
  {
   CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
   chkSel.Checked = false;
   TextBox txtname = (TextBox)gvRow.FindControl("txtName");
   TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
   txtname.ReadOnly = true;
   txtlocation.ReadOnly = true;
   txtname.ForeColor = System.Drawing.Color.Blue;
   txtlocation.ForeColor = System.Drawing.Color.Blue;
   }
  }
}

VB.NET
Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"), CheckBox)
    If chkAll.Checked = True Then
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
            chkSel.Checked = True
            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
            txtname.[ReadOnly] = False
            txtlocation.[ReadOnly] = False
            txtname.ForeColor = System.Drawing.Color.Black
            txtlocation.ForeColor = System.Drawing.Color.Black
        Next
    Else
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
            chkSel.Checked = False
            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
            txtname.[ReadOnly] = True
            txtlocation.[ReadOnly] = True
            txtname.ForeColor = System.Drawing.Color.Blue
            txtlocation.ForeColor = System.Drawing.Color.Blue
        Next
    End If
End Sub



Hope this helps.

9

GridView With ObjectDataSource Example Insert Edit Update

In this example i am explaining how to Insert Edit Update GridView With ObjectDataSource In Asp.Net 2.0,3.5,4.0. For this i've created a simple database with a table named Details having 3 columns ID,Name and Location.

Open Visual studio and create a new website. Now right click on solution explorer and select add new Item > Sql Database > name it DataBase.mdf

Create a table with columns i mentioned above in this Database.

Right click on Solution explorer and Select add new Item > choose DataSet from the dialog box

To learn how to configure database connection and connection string for this example read my article
Insert Edit Delete record in GridView using SqlDataSource ItemTemplate and EditItemTemplate


Right click on DataSet designer window and select Add > Table Adapter 


Follow the steps according to images


Use query builder to create sql statements or write ur own

Now Right click on TableAdapter and add Query for Update statement , choose Update radio button in next dialog box
Write your Update Statement


Click on finish and save the solution 

Now go to toolbox and drag a GridView on the design view of page.
Click on smart tag of GridView and choose new DataSource > Select ObjectDataSource

Select tableAdapter from the dropdown menu


Assign methods for select and update command in next dialog box

 
 
 Save the solution 


Now go to html markup of the page and change the html code of gridview according to code written below to implement ItemTemplate and EditItemTemplate

I'm using Bind method in EditItemTemplate of GridView so we do not need to write and code in CodeBehind

The html source of page should look like


<div>
<asp:GridView ID="GridView1" runat="server" 
                             AutoGenerateColumns="False" 
                             DataSourceID="ObjectDataSource1">
          
     <Columns>
     <asp:CommandField ShowEditButton="true" />
     <asp:TemplateField HeaderText="ID" SortExpression="ID">
     <EditItemTemplate>
     <asp:TextBox ID="txtID" runat="server" ReadOnly="true" 
                  Text='<%# Bind("ID") %>'>
     </asp:TextBox>
     </EditItemTemplate>       
     <ItemTemplate>
     <asp:Label ID="lblID" runat="server" BackColor="AliceBlue" 
                Text='<%# Eval("ID") %>'>
     </asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     
     <asp:TemplateField HeaderText="Name" SortExpression="Name">
     <EditItemTemplate>
     <asp:TextBox ID="txtName" runat="server" 
                  Text='<%# Bind("Name") %>'>
     </asp:TextBox>
     </EditItemTemplate>
     <ItemTemplate>
     <asp:Label ID="lblName" runat="server" BackColor="AliceBlue" 
                Text='<%# Eval("Name") %>'>
     </asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     
     <asp:TemplateField HeaderText="Locaton" 
                        SortExpression="Location">
     <EditItemTemplate>
     <asp:TextBox ID="txtLocation" runat="server" 
                  Text='<%# Bind("Location") %>'>
     </asp:TextBox>
     </EditItemTemplate>
     <ItemTemplate>
     <asp:Label ID="lblLocation" runat="server" BackColor="AliceBlue" 
                Text='<%# Eval("Location") %>'>
     </asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField>
     </Columns>
</asp:GridView>
     
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
     InsertMethod="Insert" 
     OldValuesParameterFormatString="original_{0}" 
     
     SelectMethod="GetData" 
          TypeName="DataSet1TableAdapters.DetailsTableAdapter" 
     UpdateMethod="UpdateQuery">
            <UpdateParameters>
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Location" Type="String" />
                <asp:Parameter Name="ID" Type="Decimal" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="ID" Type="Decimal" />
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Location" Type="String" />
            </InsertParameters>
        </asp:ObjectDataSource>
    </div>

Save,build and run the application

Hope this helps

Download sample code attached



Related posts:
Insert Edit Delete record in GridView using SqlDataSource

ASP.NET Edit or update multiple records/rows in gridview with checkbox

Delete multiple rows records in Gridview with checkbox and confirmation

59

Insert Update Edit Delete Rows Record In GridView

In this example i am explaining how to Insert Update Edit Delete Records Rows In GridView With SqlDataSource Using C# VB.NET Asp.Net using SqlDataSource.

For inserting record, i've put textboxes in footer row of GridView using ItemTemplate and FooterTemaplete.


Go to design view of aspx page and drag a GridView control from toolbox, click on smart tag of GridView and choose new datasource
Select Database and click Ok
 
In next screen, Enter your SqlServer name , username and password and pick Database name from the dropdown , Test the connection
 
 
 In next screen, select the table name and fields , Click on Advance tab and check Generate Insert,Edit and Delete statements checkbox , alternatively you can specify your custom sql statements 
 
 
Click on ok to finish 
Check Enable Editing , enable deleting checkbox in gridView smart tag 
Now go to html source of page and define DatakeyNames field in gridview source
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
</asp:GridView>
Remove the boundFields and put ItemTemplate and EditItemTemplate and labels and textboxs respectively, complete html source of page should look like this
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
<Columns>
    <asp:CommandField ShowDeleteButton="True" 
                      ShowEditButton="True" />
    <asp:TemplateField HeaderText="ID" SortExpression="ID">
    <ItemTemplate>
    <asp:Label ID="lblID" runat="server" 
                          Text='<%#Eval("ID") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:Button ID="btnInsert" runat="server" 
                Text="Insert" CommandName="Add" />
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="FirstName" 
                       SortExpression="FirstName">
    <ItemTemplate>
    <asp:Label ID="lblFirstName" runat="server" 
               Text='<%#Eval("FirstName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtFirstName" runat="server" 
                 Text='<%#Bind("FirstName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="LastName" 
                       SortExpression="LastName">
    <ItemTemplate>
    <asp:Label ID="lblLastName" 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="txtLname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Department" 
                       SortExpression="Department">
    <ItemTemplate>
    <asp:Label ID="lblDepartment" runat="server" 
               Text='<%#Eval("Department") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtDepartmentName" runat="server" 
                 Text='<%#Bind("Department") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtDept" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Location" 
                       SortExpression="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="txtLoc" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DBConString%>"
DeleteCommand="DELETE FROM [Employees] WHERE [ID] = @ID" 
InsertCommand="INSERT INTO [Employees] ([FirstName], 
[LastName],[Department], [Location]) 
VALUES (@FirstName, @LastName, @Department, @Location)"
SelectCommand="SELECT [ID], [FirstName], [LastName], 
[Department], [Location] FROM [Employees]"
UpdateCommand="UPDATE [Employees] SET 
[FirstName] = @FirstName, [LastName] = @LastName, 
[Department] = @Department, [Location] = @Location 
WHERE [ID] = @ID" OnInserted="SqlDataSource1_Inserted">

<DeleteParameters>
    <asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
    <asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
<asp:Label ID="lblMessage" runat="server" 
           Font-Bold="True"></asp:Label><br />
</div>
</form>
Write this code in RowCommand Event of GridView in codebehind
C# code Behind
protected void GridView1_RowCommand
(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Add")
  {
   string strFirstName = ((TextBox)
   GridView1.FooterRow.FindControl("txtFname")).Text;

   string strLastName = 
   ((TextBox)GridView1.FooterRow.FindControl
                         ("txtLname")).Text;

   string strDepartment = 
   ((TextBox)GridView1.FooterRow.FindControl
                            ("txtDept")).Text;
   string strLocation = ((TextBox)GridView1.FooterRow.
                          FindControl("txtLoc")).Text;
   //SqlDataSource1.InsertParameters.Clear();
   //SqlDataSource1.InsertParameters.Add
                       //("FirstName", strFirstName);
   //SqlDataSource1.InsertParameters.Add
                          //("LastName", strLastName);
   //SqlDataSource1.InsertParameters.Add
                         //("Department", strDepartment);
   //SqlDataSource1.InsertParameters.Add
                              //("Location", strLocation);

  SqlDataSource1.InsertParameters["FirstName"].DefaultValue 
                                             = strFirstName;
  SqlDataSource1.InsertParameters["LastName"].DefaultValue 
                                             = strLastName;
  SqlDataSource1.InsertParameters["Department"].DefaultValue 
                                             = strDepartment;
  SqlDataSource1.InsertParameters["Location"].DefaultValue
                                            = strLocation;
  SqlDataSource1.Insert();
  }
}

VB.NET Code Behind

Protected Sub GridView1_RowCommand(ByVal sender As Object, 
                       ByVal e As GridViewCommandEventArgs)
        If e.CommandName = "Add" Then
            Dim strFirstName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtFname"), TextBox).Text()

            Dim strLastName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLname"), TextBox).Text()

            Dim strDepartment As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtDept"), TextBox).Text()
            Dim strLocation As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLoc"), TextBox).Text()

            'SqlDataSource1.InsertParameters.Clear();
            'SqlDataSource1.InsertParameters.Add
            '("FirstName", strFirstName);
            'SqlDataSource1.InsertParameters.Add
            '("LastName", strLastName);
            'SqlDataSource1.InsertParameters.Add
            '("Department", strDepartment);
            'SqlDataSource1.InsertParameters.Add
            '("Location", strLocation);

            SqlDataSource1.InsertParameters("FirstName").
            DefaultValue = strFirstName
            SqlDataSource1.InsertParameters("LastName").
            DefaultValue = strLastName
            SqlDataSource1.InsertParameters("Department").
            DefaultValue = strDepartment
            SqlDataSource1.InsertParameters("Location").
            DefaultValue = strLocation
            SqlDataSource1.Insert()
        End If
    End Sub


Download the sample code attached


You would also like to read
Edit or update multiple records/rows in gridview with checkbox using C# in ASP.NET

Delete multiple rows records in Gridview with checkbox and confirmation in ASP.NET

Find More Articles