ASP.NET - Inserting Data in gridview

Asked By sharad mishra
13-Oct-11 05:35 AM
I want to insert data in gridview using templates for which I hav written d following code:

<Columns>
          <asp:CommandField ShowEditButton="True" ShowDeleteButton="true" ShowCancelButton="true"
            HeaderText="Edit" />
          <asp:TemplateField>
            <FooterTemplate>
              <asp:LinkButton ID="lbInsert" runat="server" OnClick="lbInsert_Click">Insert</asp:LinkButton>
              <asp:LinkButton ID="lbCancel" runat="server" OnClick="lbCancel_Click">Cancel</asp:LinkButton>
            </FooterTemplate>
          </asp:TemplateField>
</Columns>

I hav 2 tables..Table_1 and Table_2
with (ID(PK),Name) and (ID,Table1_ID(FK),Name_1 and Name_2) respectively

Plz help me out for that..
I want that when I click on Insert Link Button then textbox comes on footer for filling data and for the rest tym it remains hidden. i am using stored procedure rather than query.
Thnx in advance

  Reena Jain replied to sharad mishra
13-Oct-11 05:39 AM
Hi,

The below sample show the grid view inserting records from the footer template...

<%@ Page Language="C#" Theme="" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
 
<!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" xml:lang="en" lang="en">
  <head id="Head1" runat="server">
   <title>ASP.NET Insert data in Gridview </title>
  </head>
<body>
   <form id="form1" runat="server">
  <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
  <asp:GridView ID="GridView1" ShowFooter="true" runat="server"   
   OnRowCommand="GridView1_RowCommand1" AutoGenerateColumns="false">
  <Columns>
   <asp:TemplateField>
    <ItemTemplate>
     <asp:Button Text="Edit" CommandName="Edit" CausesValidation="false" runat="server" ID="btEdit" /> 
     <asp:Button Text="Delete" CommandName="Delete" CausesValidation="false" runat="server" ID="btDelete" />
    </ItemTemplate>
    <EditItemTemplate>
     <asp:Button Text="Update" CommandName="Update" CausesValidation="true" runat="server" ID="btUpdate" /> 
     <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" />
    </EditItemTemplate>
    <FooterTemplate>
     <asp:Button Text="Insert" CommandName="Insert" CausesValidation="true" runat="server" ID="btInsert" /> 
     <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" />
    </FooterTemplate>
   </asp:TemplateField>
     <asp:TemplateField >
    <ItemTemplate>
     <asp:Label ID="lblValue" Text='<%# Eval("Name") %>' runat="server"></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
      <asp:TextBox ID="tbUpdate" runat="server" Text='<% Bind("Name") %>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
      <asp:TextBox ID="tbInsert" runat="server" Text="" ></asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
   </Columns>
   <EmptyDataTemplate>
     <asp:TextBox ID="tbEmptyInsert" runat="server"></asp:TextBox><br />
     <asp:Button ID="btSend" Text="Insert" runat="server" CommandName="EmptyInsert" UseSubmitBehavior="False" />
    </EmptyDataTemplate>
   </asp:GridView>
  </form>
   </body>
</html>

And the code behind :

public partial class Test : System.Web.UI.Page
 
  {
 
    protected void Page_Load(object sender, EventArgs e)
 
    {
 
      if (!IsPostBack)
 
      {
 
        //Create dummy data
 
        DataTable dt = new DataTable();
 
        DataColumn dc = new DataColumn("Name");
 
        dt.Columns.Add(dc);
 
        DataRow dr = dt.NewRow();
 
        dr["Name"] = "Ivan";
 
    
 
        //Uncomment the following line to have data in the grid :)
 
        //dt.Rows.Add(dr);
 
    
 
        //Bind the gridview
 
        GridView1.DataSource = dt;
 
        GridView1.DataBind();
 
      }
 
      //Recurses through the controls to show the naming of each individual control that is currently in the gridview
 
      RecurseControls(GridView1.Controls[0].Controls);
 
      Label1.Text += GridView1.Controls[0].Controls[0].GetType().Name + "<br />";
 
    }
 
    
 
    void RecurseControls(ControlCollection ctls)
 
    {
 
      foreach (Control ctl in ctls)
 
      {
 
        if (!ctl.HasControls())
 
          Label1.Text += ctl.ClientID + " " + ctl.GetType().Name + "<br />";
 
        else
 
          RecurseControls(ctl.Controls);
 
      }
 
    }
 
    
 
    protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
 
    {
 
      if (e.CommandName == "EmptyInsert")
 
      {
 
        //handle insert here
 
        TextBox tbEmptyInsert = GridView1.Controls[0].Controls[0].FindControl("tbEmptyInsert") as TextBox;
 
   56       Label1.Text = string.Format("You would have inserted the name : <b>{0}</b> from the emptydatatemplate",tbEmptyInsert.Text);
 
    
 
      }
 
      if (e.CommandName == "Insert")
 
      {
 
        //handle insert here
 
        TextBox tbInsert = GridView1.FooterRow.FindControl("tbInsert") as TextBox;
 
        Label1.Text = string.Format("You would have inserted the name :  <b>{0}</b> from the footerrow", tbInsert.Text);
 
      }
 
     }
   }

  smr replied to sharad mishra
13-Oct-11 06:13 AM
HI

refer this

<p style="text-align:right;"><asp:Button ID="btnAdd" runat="Server" Text="Add New Record" OnClick="AddNewRecord" /></p>

<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False"

BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"

CellPadding="4" ForeColor="Black" GridLines="Vertical" SkinID="RecordList" Width="100%"

OnRowCommand="GridView1_OnRowCommand1" ShowFooter="False" AutoGenerateEditButton="true" OnRowEditing="EditRecord" OnRowCancelingEdit="CancelRecord"

OnRowUpdating="UpdateRecords" DataKeyNames="AutoID" EnableViewState="True">

<Columns>

<asp:BoundField DataField="AutoID" HeaderText="AutoID" ReadOnly="True" />

<asp:TemplateField HeaderText="UserName">

<ItemTemplate>

<%# Eval("UserName") %>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtUserName" runat="Server" Text='<%# Eval("UserName") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtUserName" runat="Server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Password">

<ItemTemplate>

<%# Eval("Password") %>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtPassword" runat="Server" Text='<%# Eval("Password") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtPassword" runat="Server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="SuperPassword">

<ItemTemplate>

<%# Eval("SuperPassword") %>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtSuperPassword" runat="Server" Text='<%# Eval("SuperPassword") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtSuperPassword" runat="Server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="UserType">

<ItemTemplate>

<%# Eval("UserType") %>

</ItemTemplate>

<EditItemTemplate>

<asp:DropDownList ID="dropType" runat="server" SelectedValue='<%# Eval("UserType").ToString() %>'>

<asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>

<asp:ListItem Text="Maint" Value="Maint"></asp:ListItem>

</asp:DropDownList>

</EditItemTemplate>

<FooterTemplate>

<asp:DropDownList ID="dropType" runat="server">

<asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>

<asp:ListItem Text="Maint" Value="Maint"></asp:ListItem>

</asp:DropDownList>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="AdminDesc">

<ItemTemplate>

<%# Eval("AdminDesc") %>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtAdminDesc" Columns="30" runat="Server" Text='<%# Eval("AdminDesc") %>'></asp:TextBox>

</EditItemTemplate>

<FooterTemplate>

<asp:TextBox ID="txtAdminDesc" runat="Server" Text='<%# Eval("AdminDesc") %>'></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Active">

<ItemTemplate>

<%# Eval("Active") %>

</ItemTemplate>

<EditItemTemplate>

<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active").ToString().ToLower().Equals("true") ? "True" : "False" %>'>

<asp:ListItem Text="Yes" Value="True"></asp:ListItem>

<asp:ListItem Text="No" Value="False"></asp:ListItem>

</asp:DropDownList>

</EditItemTemplate>

<FooterTemplate>

<asp:DropDownList ID="dropActive" runat="server">

<asp:ListItem Text="Yes" Value="True"></asp:ListItem>

<asp:ListItem Text="No" Value="False"></asp:ListItem>

</asp:DropDownList> <br />

<asp:Button ID="btnInsert" runat="Server" Text="Insert" CommandName="Insert" UseSubmitBehavior="False" />

</FooterTemplate>

</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

<EmptyDataTemplate>

UserName <asp:TextBox ID="txtUserName" runat="Server"></asp:TextBox> Password <asp:TextBox ID="txtPassword" runat="Server"></asp:TextBox> SuperPassword <asp:TextBox ID="txtSuperPassword" runat="Server"></asp:TextBox>

User Type <asp:DropDownList ID="dropType" runat="server">

<asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>

<asp:ListItem Text="Maint" Value="Maint"></asp:ListItem>

</asp:DropDownList> Admin Desc <asp:TextBox ID="txtAdminDesc" runat="Server" /> Active <asp:DropDownList ID="dropActive" runat="server">

<asp:ListItem Text="Yes" Value="True"></asp:ListItem>

<asp:ListItem Text="No" Value="False"></asp:ListItem>

</asp:DropDownList>

<asp:Button ID="btnInsert" runat="Server" Text="Insert" CommandName="EmptyInsert" UseSubmitBehavior="False" />

</EmptyDataTemplate>

</asp:GridView>




When Insert Button of the form will be clicked

protected void GridView1_OnRowCommand1(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName.Equals("EmptyInsert"))

{

TextBox u = GridView1.Controls[0].Controls[0].FindControl("txtUserName") as TextBox;

TextBox p = GridView1.Controls[0].Controls[0].FindControl("txtPassword") as TextBox;

TextBox sp = GridView1.Controls[0].Controls[0].FindControl("txtSuperPassword") as TextBox;

DropDownList dT = GridView1.Controls[0].Controls[0].FindControl("dropType") as DropDownList;

TextBox ad = GridView1.Controls[0].Controls[0].FindControl("txtAdminDesc") as TextBox;

DropDownList dA = GridView1.Controls[0].Controls[0].FindControl("dropActive") as DropDownList;

 

new AdminBAL().Insert(u.Text, p.Text, sp.Text, dT.SelectedValue, ad.Text, bool.Parse(dA.SelectedValue));

lblError.Text = "<br />Record inserted successfully<br />";

BindCurrentUsers(); // rebind the dat

}

if (e.CommandName.Equals("Insert"))

{

TextBox u = GridView1.FooterRow.FindControl("txtUserName") as TextBox;

TextBox p = GridView1.FooterRow.FindControl("txtPassword") as TextBox;

TextBox sp = GridView1.FooterRow.FindControl("txtSuperPassword") as TextBox;

DropDownList dT = GridView1.FooterRow.FindControl("dropType") as DropDownList;

TextBox ad = GridView1.FooterRow.FindControl("txtAdminDesc") as TextBox;

DropDownList dA = GridView1.FooterRow.FindControl("dropActive") as DropDownList;

 

new AdminBAL().Insert(u.Text, p.Text, sp.Text, dT.SelectedValue, ad.Text, bool.Parse(dA.SelectedValue));

lblError.Text = "<br />Record inserted successfully<br />";

BindCurrentUsers(); // rebind the data

}

}


follow http://www.dotnetfunda.com/articles/article180.aspx

  dipa ahuja replied to sharad mishra
13-Oct-11 06:15 AM
Untitled document
Step 1 : Add new template Field With the Required Controls:
 
<asp:TemplateField>
<FooterTemplate>
 Name:<asp:TextBox ID="txtname" runat="server" /><br />
 Gender :
 <asp:DropDownList ID="ddGender" runat="server">
   <asp:ListItem>Male</asp:ListItem>
   <asp:ListItem>Female</asp:ListItem>
 </asp:DropDownList>
       
  <asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" />
</FooterTemplate>
</asp:TemplateField>
  
► Step 2 Implement the Button's Click event:
protected void btnInsert_Click(object sender, EventArgs e)
{
 string name = ((TextBox)GridView1.FooterRow.FindControl("txtname")).Text;
 string gender = ((DropDownList)GridView1.FooterRow.FindControl("ddGender")).SelectedValue;
  string ConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 SqlConnection conn = new SqlConnection(ConnString);
   
  conn.Open();
   
  string q = "insert into people (name,gender) values(@name,@gender)";
 SqlCommand comm = new SqlCommand(q,conn);
  comm.Parameters.AddWithValue("name", name);
 comm.Parameters.AddWithValue("gender", gender);
 comm.ExecuteNonQuery();
 conn.Close();
  BindGrid(); //Re-bind Gridview
}
  sharad mishra replied to dipa ahuja
13-Oct-11 07:18 AM
The first problem I hav encountered is that the footer template containing the link buttons(insert and cancel) are visible in the design mode but they are not showing up in the browser at runtime..:(

ny idea why is this happening.?
Create New Account
help
SqlParameters to be assigned values< / param> / / / <param name = "dataRow"> The dataRow used to hold the stored procedure's parameter values< / param> private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow) { if ((commandParameters = = null param> / / / <param name = "transaction"> A valid SqlTransaction, or 'null'< / param> / / / <param name = "commandType"> The CommandType (stored procedure, text, etc.)< / param> / / / <param name = "commandText"> The stored procedure name or T-SQL command< / param> / / / <param name = "commandParameters"> An array of SqlParameters to be mustCloseConnection = false; } / / Associate the connection with the command command.Connection = connection; / / Set the command text (stored procedure name or SQL statement) command.CommandText = commandText; / / If we were provided a transaction, assign it
alot var Hi What are Master Pages in ASP.NET? or What is a Master Page? ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page. What are the 2 important parts of a master page? The following are the 2 important parts of a master page 1. The Master Page itself 2. One or more Content Pages Can Master Pages be nested? Yes, Master Pages
all this in details. actually m not knowing anything about all this Post your login page code, we shall start from there <% @ Page Language = "C#" AutoEventWireup = "true" CodeFile = "Login.aspx.cs" Inherits = "_Default" %> <! DOCTYPE html PUBLIC "- / / W3C / / DTD 003300" > < / asp : Label > < / td > < td align = "center" style = "background-color: ActiveBorder; width: 312px;"> &nbsp; < asp : DropDownList ID = "DropDownList1" runat = "server" Style = "z-index: 100; left: 275px; position: absolute; top: 147px" Width ListItem Selected = "True" Text = "User" Value = ""> < / asp : ListItem > < asp : ListItem > Reporting Officer < / asp : ListItem > < / asp : DropDownList > < / td > < tr > < td colspan = '2' style = "background-color:Gray;height: 26px" align = "center"> < asp : Button how to do all the work, so plz help me to run this whole login page. . . <% @ Page Language = "C#" AutoEventWireup = "true" CodeFile = "Login.aspx.cs" Inherits = "_Default" %> <! DOCTYPE html PUBLIC "- / / W3C / / DTD 003300" > < / asp : Label > < / td > < td align = "center" style = "background-color: ActiveBorder; width: 312px;"> &nbsp; < asp : DropDownList ID = "DropDownList1" runat = "server" Style = "z-index: 100; left: 275px; position: absolute; top: 147px" Width ListItem Selected = "True" Text = "User" Value = ""> < / asp : ListItem > < asp : ListItem > Reporting Officer < / asp : ListItem > < / asp : DropDownList > < / td > < tr > < td colspan = '2' style = "background-color:Gray;height: 26px" align = "center"> < asp : Button
how do you go about it? (A) What is Manifest? (B) Where is version information stored of an assembly? (I) Is versioning applicable to private assemblies? (B) What is GAC? (I using cache object of ASP.NET? (B) How can you cache different version of same page using ASP.NET cache object? (A) How will implement Page Fragment Caching? (B) Can you compare ASP.NET sessions with classic ASP? (B) Which are of using Query Strings? (I) What is Absolute and Sliding expiration? (I) What is cross page posting? 93 (I) How do we access viewstate value of this page in the next page ? (I) Can we post and access view state in another application? (I) What is SQL In which event are the controls fully loaded? (B) How can we identify that the Page is Post Back? (B) How does ASP.NET maintain state in between subsequent request? (A) What is event bubbling? B) How do we assign page specific attributes? (A) How do we ensure viewstate is not tampered? (B) What is the