ASP.NET - insert  ASP.NET - insert

Asked By wwww rrwr
02-Jul-11 07:19 AM
how to  insert in gridview
  Reena Jain replied to wwww rrwr
02-Jul-11 07:57 AM
hi,

here is the code for you

on .aspx page
<tr>
<td width="100" align="right" bgcolor="#eeeeee" class="header1"> Employee Data Using the GridView Control:</td>
<td align="center" bgcolor="#FFFFFF">
<asp:GridView ID="gvwExample" runat="server" AutoGenerateColumns="False" CssClass="basix" >
<columns>
<asp:BoundField DataField="firstname" HeaderText="First Name" />
<asp:BoundField DataField="lastname" HeaderText="Last Name" />
<asp:BoundField DataField="hiredate" HeaderText="Date Hired" />
</columns>
</asp:GridView>
<asp:label ID="lblStatus" runat="server"></asp:label></td>
</tr>

on .aspx.cs page
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
  
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT firstname,lastname,hiredate FROM EMPLOYEES", new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;"));
  
try
{
cmd.Connection.Open();
  
gvwExample.DataSource = cmd.ExecuteReader();
  
gvwExample.DataBind();
  
cmd.Connection.Close();
cmd.Connection.Dispose();
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
}


hope this will help you
  Web Star replied to wwww rrwr
02-Jul-11 08:14 AM
You can use Insert Command
1. create a database and table Customers with 4 colums [Customers] ([CustomerID], [CompanyName], [ContactTitle]) , and insert some records to the table
2. create connect string "ConnString"
3. create a aspx file and copy paste the code to your file

<%@ Page Language="C#" ClassName="Default_aspx" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

 

<script runat="server">

void Button1_Click(object sender, EventArgs e)

{

TextBox customerID = GridView1.FooterRow.FindControl("CustomerIDTextBox") as TextBox;

TextBox companyName = GridView1.FooterRow.FindControl("CompanyNameTextBox") as TextBox;

DropDownList ContactTitle = GridView1.FooterRow.FindControl("ContactTitleDropDownList") as DropDownList;

 

SqlDataSource1.InsertParameters["CustomerID"].DefaultValue = customerID.Text;

SqlDataSource1.InsertParameters["CompanyName"].DefaultValue = companyName.Text;

SqlDataSource1.InsertParameters["ContactTitle"].DefaultValue = ContactTitle.SelectedValue;

 

SqlDataSource1.Insert();

}

 

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID"

AutoGenerateColumns="False" ShowFooter="True" >

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="CustomerIDLabel" Runat="Server"><%# Eval("CustomerID") %></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="CustomerIDTextBox" Runat="server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="CompanyNameLabel" Runat="Server"><%# Eval("CompanyName") %></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="CompanyNameTextBox" Runat="server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField>

<FooterTemplate>

<asp:DropDownList ID="ContactTitleDropDownList" Runat="server" DataSourceID="SqlDataSource2" DataTextField="ContactTitle" DataValueField="ContactTitle">

</asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:ConnString%>">

</asp:SqlDataSource>

<asp:Button ID="Button1" Runat="server" Text="Add" OnClick="Button1_Click" />

</FooterTemplate>

<ItemTemplate>

<asp:DropDownList ID="ContactTitleDropDown" SelectedValue='<%# Bind("ContactTitle") %>' Runat="Server" DataSourceID="SqlDataSource3" DataTextField="ContactTitle" DataValueField="ContactTitle" ></asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource3" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:ConnString%>" EnableCaching="True">

</asp:SqlDataSource>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"

InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactTitle)"

SelectCommand="SELECT [CustomerID], [CompanyName], [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:ConnString%>">

<DeleteParameters>

<asp:Parameter Type="String" Name="CustomerID"></asp:Parameter>

</DeleteParameters>

<UpdateParameters>

<asp:Parameter Type="String" Name="CompanyName"></asp:Parameter>

<asp:Parameter Type="String" Name="ContactTitle"></asp:Parameter>

<asp:Parameter Type="String" Name="CustomerID"></asp:Parameter>

</UpdateParameters>

<InsertParameters>

<asp:Parameter Type="String" Name="CustomerID"></asp:Parameter>

<asp:Parameter Type="String" Name="CompanyName"></asp:Parameter>

<asp:Parameter Type="String" Name="ContactTitle"></asp:Parameter>

</InsertParameters>

</asp:SqlDataSource>

</div>

</form>

</body>

</html>

  dipa ahuja replied to wwww rrwr
02-Jul-11 08:25 AM
Gridview does support the the insert event so we need to implement the insert query by coding..

protected void Button1_Click(object sender, EventArgs e)
{
  if (TextBox1.Text != "" && TextBox2.Text != "")
  {
    string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 
    SqlConnection conn = new SqlConnection(conString);
 
    string query = "Insert Into table1 (name,country) values (@name,@country)";
 
    conn.Open();
 
    SqlCommand comm = new SqlCommand(query, conn);
 
    comm.Parameters.AddWithValue("name", TextBox1.Text);
    comm.Parameters.AddWithValue("country", TextBox2.Text);
    comm.ExecuteNonQuery();
 
    conn.Close();
    //Rebind GridView
  }    
}


  [ Kirtan ] replied to wwww rrwr
02-Jul-11 10:51 AM
Untitled document
GridView does not have add() method like dataGridView of windows Form have .
so instead of adding row to GridView you need to add row to DataTable that is provided as datasource in GridView before binding it if you want to add new row to it .
 
here is how you can do it

 
protected void Button1_Click(object sender, EventArgs e)
{
   SqlConnection con = new SqlConnection("Connection String");
   con.Open();
   SqlCommand comm = new SqlCommand("select * from Table", con);
   DataTable dt = new DataTable();
   SqlDataAdapter da = new SqlDataAdapter(comm);
   da.Fill(dt);
   con.Close();
 
  /* Add New Row to DataTable instead of Gridview */
   DataRow r = dt.NewRow();
   r[0] = "Col1Value";
   r[1] = "Col2Value";
   .
   .
   .
   /* and so as as per your columns */
 
   GridView1.DataSource = dt;
   DataBind();
}
 
 
  Riley K replied to wwww rrwr
02-Jul-11 10:16 PM
Check these links, lots of examples


http://www.eggheadcafe.com/community/aspnet/17/10320776/gridview-inserteditupdatedelete-data-using-stored-procedures.aspx

http://www.codeproject.com/KB/aspnet/InsertingWithGridView.aspx

http://www.codeproject.com/KB/aspnet/ExtendedGridView.aspx

http://geekswithblogs.net/casualjim/articles/51360.aspx

http://www.dotnetfunda.com/articles/article180.aspx
  Ravi S replied to wwww rrwr
04-Jul-11 03:08 AM
HI

try this

public partial class Test : System.Web.UI.Page

   15 {

   16   protected void Page_Load(object sender, EventArgs e)

   17   {

   18       if (!IsPostBack)

   19       {

   20           //Create dummy data

   21           DataTable dt = new DataTable();

   22           DataColumn dc = new DataColumn("Name");

   23           dt.Columns.Add(dc);

   24           DataRow dr = dt.NewRow();

   25           dr["Name"] = "Ivan";

   26 

   27           //Uncomment the following line to have data in the grid :)

   28           //dt.Rows.Add(dr);

   29 

   30           //Bind the gridview

   31           GridView1.DataSource = dt;

   32           GridView1.DataBind();

   33       }

   34       //Recurses through the controls to show the naming of each individual control that is currently in the gridview

   35       RecurseControls(GridView1.Controls[0].Controls);

   36       Label1.Text += GridView1.Controls[0].Controls[0].GetType().Name + "<br />"

   37   }

   38 

   39   void RecurseControls(ControlCollection ctls)

   40   {

   41       foreach (Control ctl in ctls)

   42       {

   43           if (!ctl.HasControls())

   44               Label1.Text += ctl.ClientID + " " + ctl.GetType().Name + "<br />";

   45           else

   46               RecurseControls(ctl.Controls);

   47       }

   48   }

   49 

   50   protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)

   51   {

   52       if (e.CommandName == "EmptyInsert")

   53       {

   54           //handle insert here

   55           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);

   57 

   58       }

   59       if (e.CommandName == "Insert")

   60       {

   61           //handle insert here

   62           TextBox tbInsert = GridView1.FooterRow.FindControl("tbInsert") as TextBox;

   63           Label1.Text = string.Format("You would have inserted the name :  <b>{0}</b> from the footerrow", tbInsert.Text);

   64       }

   65   }

   66 

   67 }



refer the links for more examples
http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx
http://www.knowlegezone.com/documents/70/ASPNET-Formview--GridView-Coltrol-Insert-Update-Paging-And-Delete/
http://www.aspdotnetfaq.com/Faq/How-to-insert-row-in-GridView-with-SqlDataSource.aspx
  Vickey F replied to wwww rrwr
04-Jul-11 05:18 AM
GridView doesn't provide inbuilt functionality for inserting record, you have to implement this feature
by own.

try this code-

For inserting using GridView Follow this code-

.ASPX code=

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>GridView Data Manipulation</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <table cellpadding="0" cellspacing="0">

      <tr>

      <td style="width: 100px; height: 19px;">

        Company ID</td>

      <td style="width: 100px; height: 19px;">

        Company</td>

      <td style="width: 100px; height: 19px;">

        Name</td>

      <td style="width: 100px; height: 19px;">

        Title</td>

      <td style="width: 100px; height: 19px;">

        Address</td>

      <td style="width: 100px; height: 19px;">

        Country</td>

      </tr>

      <tr>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox1" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox2" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox3" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox4" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox5" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox6" runat="server"/></td>

      <td style="width: 100px">

        <asp:Button ID="Button1" runat="server" Text="Add New" OnClick="Button1_Click" /></td>

      </tr>

    </table>

   

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">

    <Columns>

      <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="true"/>

      <asp:BoundField DataField="CompanyName" HeaderText="Company"/>

      <asp:BoundField DataField="ContactName" HeaderText="Name"/>

      <asp:BoundField DataField="ContactTitle" HeaderText="Title" />

      <asp:BoundField DataField="Address" HeaderText="Address"/>

      <asp:BoundField DataField="Country" HeaderText="Country"/>

    </Columns>

    </asp:GridView>

    </div>

    </form>

</body>

</html>

.CS Code-

#region Insert New or Update Record

    private void UpdateOrAddNewRecord(string ID, string Company, string Name, string Title, string Address, string Country, bool isUpdate)

    {

    SqlConnection connection = new SqlConnection(GetConnectionString());

    string sqlStatement = string.Empty;

    if (!isUpdate)

    {

      sqlStatement = "INSERT INTO Customers"+

"(CustomerID,CompanyName,ContactName,ContactTitle,Address,Country)" +

"VALUES (@CustomerID,@CompanyName,@ContactName,@ContactTitle,@Address,@Country)";

    }

    else

    {

      sqlStatement = "UPDATE Customers" +

         "SET CompanyName = @CompanyName,

         ContactName = @ContactName," +

         "ContactTitle = @ContactTitle,Address = 

         @Address,Country = @Country" +

         "WHERE CustomerID = @CustomerID,";

    }

    try

    {

      connection.Open();

      SqlCommand cmd = new SqlCommand(sqlStatement, connection);

      cmd.Parameters.AddWithValue("@CustomerID", ID);

      cmd.Parameters.AddWithValue("@CompanyName", Company);

      cmd.Parameters.AddWithValue("@ContactName", Name);

      cmd.Parameters.AddWithValue("@ContactTitle", Title);

      cmd.Parameters.AddWithValue("@Address", Address);

      cmd.Parameters.AddWithValue("@Country", Country);

      cmd.CommandType = CommandType.Text;

      cmd.ExecuteNonQuery();

    }

    catch (System.Data.SqlClient.SqlException ex)

    {

      string msg = "Insert/Update Error:";

      msg += ex.Message;

      throw new Exception(msg);

    }

    finally

    {

      connection.Close();

    }

    }

    #endregion

Try an dlet me know . 

Create New Account
help
Bold = "True" HorizontalAlign = "Center" / > <PagerStyle BackColor = "#E0E0E0" Font-Bold = "True" ForeColor = "White" / > < / asp:GridView> <asp:DropDownList ID = "ddlRooms" runat = "server" CssClass = "inputty2" AutoPostBack = "True" OnSelectedIndexChanged = "ddlRooms_SelectedIndexChanged"> <asp:ListItem> 1< / asp:ListItem ListItem> 8< / asp:ListItem> <asp:ListItem> 9< / asp:ListItem> <asp:ListItem> 10< / asp:ListItem> < / asp:DropDownList> .cs coding: - -- -- -- -- -- -- -- -- protected void lbtnNext_Click(object sender, EventArgs e) { / / [B]here i want to goto outside of Gridview.[ / B] Response.Redirect("DetailedView.aspx?hn = "+lbtnNext.Text+"&R = "+ddlRooms.SelectedItem.ToString()); } Error 4 The name 'lbtnNext' does not exist in the current context thanks in advance Hi ConnectionString")) 18. { 19. using (SqlCommand command = new SqlCommand("Select * from Products", connection)) 20. { 21. using (SqlDataAdapter da = new SqlDataAdapter(command)) { 22. DataTable dt = new DataTable(); 23. da.Fill(dt); 24. GridView1.DataSource = dt; 25 GridView1.DataBind(); 26. } 27. } 28. } 29. } 30. 31. protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 32. { 33. if (e.CommandName = = "goto") 34. { 35. string queryString = "hn = " + e.CommandArgument.ToString server" > 46. < div > 47. < asp:ScriptManager ID = "sm" runat = "server" > 48. < / asp:ScriptManager > 49. < asp:DropDownList ID = "ddl" runat = "server" > 50. < asp:ListItem Text = "Item1" > < / asp:ListItem > 51. < asp:ListItem Text asp:ListItem Text = "Item4" > < / asp:ListItem > 54. < asp:ListItem Text = "Item5" > < / asp:ListItem > 55. < / asp:DropDownList > 56. < asp:GridView ID = "GridView1" runat = "server" onrowcommand = "GridView1_RowCommand" > 57. < Columns > 58. < asp:TemplateField > 59
BoundField DataField = "empname" HeaderText = "empname" / > <asp:TemplateField HeaderText = "dept"> <ItemTemplate> <%# Eval("dep") %> < / ItemTemplate> <EditItemTemplate> <asp:DropDownList runat = "server" DataSourceID = "SqlDataSource1" ID = "DropDeptId" DataTextField = "Deptid" DataValueField = "DeptId" / > < / EditItemTemplate> < / asp:TemplateField> <asp:CommandField SqlConnection("Data Source = 10.0.2.8;Initial Catalog = JitendraDB;User ID = sa;password = change_123"); SqlDataAdapter da; string mySQL = "SELECT empid, empname, dept FROM emp "; da = new SqlDataAdapter(mySQL, con); con.Open(); DataSet ds = new DataSet(); da.Fill(ds); GridView2.DataSource = ds; GridView2 ENPID string strEmpName = GridView1.Rows[e.RowIndex].Cells[2].Text; / / FOR GETTING ENPNAME string strDeptId = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDeptId")).SelectedValue.ToString(); string UpdateQuery = "update emp set empname = '" + strEmpName aspx http: / / www.asp.net / data-access / tutorials / inserting-updating-and-deleting-data-with-the-sqldatasource-vb HI PLEASE SEE THIS EXAMPLE < table class = "style1" > < tr > < td class = "style2" > Album Name inside the code. String fn; String path; SqlConnection cnn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); SqlDataAdapter adp; DataTable dt; Int32 id; / / id as a integer variable it will be used to am using the sql query to select the gecord from the database and adp = new SqlDataAdapter( "SELECT * FROM tb_gallery " , cnn); / / here i declare the datatable to fill the record dt = new sql query to select the record that will be selected by the user for deletion SqlDataAdapter adp = new SqlDataAdapter( "select * from tb_gallery where id = @id" , cnn); / / here i am passing the
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 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 Efficiency < / td > < td > < / td > < / tr > < tr > < td style = "width: 137px; height: 37px" align = "center"> < asp : DropDownList ID = "DDtech1" runat = "server" Style = "z-index: 100; left: 36px; position: absolute; top: 79px"> < asp : ListItem > Select < / asp : ListItem > < asp : ListItem > ASP < / asp : ListItem > < / asp : DropDownList > < / td > < td style = "width: 129px; height: 37px" align = "center"> < asp DropDownList ID = "DDSkillLevel1" runat = "server" Style = "z-index: 100; left: 171px; position: absolute; top: 80px"> < asp : ListItem > Select < / asp : ListItem > < / asp : DropDownList > < / td > < td style = "width: 146px; height: 37px" align = "center"> < asp : TextBox ID = "txtDuration1" runat = "server
Error Handling in a called function Hi Guys, A quick question for you. I have a Sub which calls a Function several times. Both the Sub & Function have error handling. The problem is, when there is an error in the called Function, the calling Sub Error Handler fires. How can I get the Function Error Handler to fire? Cheers Pete You can return a boolean from the Function to indicate whther it was successful. For example: Private Sub SendTrades() On Error GoTo Err_Handler 'do some stuff If EmailTrades(parameters) Then 'Do more stuff. . . . Else MsgBox "Problem Description Resume Err_Resume End Sub Public Function EmailTrades(ByVal parameters as blah) As Boolean On Error GoTo Err_Handler 'do some emailing stuff. If it fails here, the function will return false will help you. Hi Vickey, Thanks for the speedy reply. In the function where the error occurs, I don't want it to return a boolean and exit. There is other