ASP.NET - import data from aspxgridview to Database

Asked By Bookworm
04-Aug-11 04:51 AM
Hi,
How can i import data  from aspxgridview to a table in my Database?

how can i get the cell value?

thnx in advance
  Vickey F replied to Bookworm
04-Aug-11 04:54 AM

try this

You can loop through the whole GridView, and get data from each row. Then insert these data (each row) into test table row by row. Here is my sample:

protected void SaveButton(object sender, EventArgs e)
    {
    SqlConnection conn = new SqlConnection(@"your_connection_string");
    conn.Open();
    foreach (GridViewRow gvr in GridView1.Rows)
    {
      string data1 = gvr.Cells[0].Text;    //get data from BoundField in each row
      string data2 = ((Label)gvr.FindControl("Label1")).Text;    //get data from control in TemplateField in each row
      SqlCommand cmd = new SqlCommand("insert_sql", conn);   //generate insert sql using above data
      cmd.ExecuteNonQuery();
    }
    conn.Close();
    }

Hope this will help you.

  dipa ahuja replied to Bookworm
04-Aug-11 05:01 AM
Hi.. we are binding the griview form the database , and the gridveiw contains data of database table or other datatable .. 

but still if you want to store data of that then try this code:


 
Take a Button to pass data to next Page
 
<asp:Button ID="btnTransfer" runat="server" onclick="btnTransfer_Click"
  Text="Send" />
 
Write this code in the Button click
 
  protected void btnTransfer_Click(object sender, EventArgs e)
  {     
    SqlConnection conn = new SqlConnection("Connstring");
    SqlCommand comm;
    foreach (GridViewRow row in GridView1.Rows)
    {
      //Get data of ItemTEmplate of table Fields
      string lblname = ((Label)row.FindControl("lblName")).Text;
      string lblgender = ((Label)row.FindControl("lblGender")).Text;
 
      string q = "insert into tabl1 (name,gender) values('" + lblname + "','"
         + lblgender + "')";
      comm = new SqlCommand(q, conn);
 
      conn.Open();
 
      comm.ExecuteNonQuery();
 
      conn.Close();
    }
  }
  James H replied to Bookworm
04-Aug-11 05:18 AM
HI
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

YOU CAN INSERT THE DATA FROM GRIDVIEW TO DATABASE LIKE THIS
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();
}
<%@ 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">
</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>


  TSN ... replied to Bookworm
04-Aug-11 05:49 AM
hi..
try this..
Public Function PutBondInfo(ByVal data As String) As DataSet
      Try
        Dim zh As New ZipHelper
        Dim sz As String
        Dim cn As SqlConnection
        Dim da As SqlDataAdapter
        Dim ds As New DataSet
        Dim xSet As New DataSet
        Dim sSql As String

        Dim mySerializer As XmlSerializer = New
XmlSerializer(ds.GetType())

        cn = New
SqlConnection("server=HLSQL;uid=test;pwd=;database=test")
        cn.Open()
        da = New SqlDataAdapter("SELECT * FROM BondStatus", cn)
        'da.TableMappings.Add("BondStatus", "NewDataSet")

        sz = zh.Decompress(data)
        zh = Nothing

        da.FillSchema(ds, SchemaType.Mapped, "BondStatus")
        'da.MissingSchemaAction = MissingSchemaAction.AddWithKey
        da.Fill(ds, "BondStatus")

        Dim st As New MemoryStream(Encoding.UTF8.GetBytes(sz))
        ' Create the object from the xml file
        xSet = CType(mySerializer.Deserialize(st), DataSet)
        xSet.Tables(0).TableName = ds.Tables(0).TableName

        ds.Merge(xSet, False, System.Data.MissingSchemaAction.Add)

        'ds.AcceptChanges()

        Dim SqlCB As SqlCommandBuilder = New SqlCommandBuilder(da)
        da.Update(ds, "BondStatus")

        st.Close()
        da.Dispose()
        SqlCB.Dispose()
        cn.Close()

        Return ds
      Catch ex As Exception
        ex.Message().ToString()
      End Try

    End Function
Create New Account
help
Net hi friends Any one send frequently asked Important questions in C# .Net, ADO .Net, Asp .Net and Sql Server. . . . . . . . tx in Advance. . . . . . Hi, Find this. . (B)What is an IL? (B Daemon threads and how can a thread be created as Daemon? (A) How is shared data managed in threading? (I) Can we use events with threading? (A) How can we know A) What is scavenging? (B) What are different types of caching 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 the various modes of storing ASP.NET
replace the ADO Recordset object? The differences includes In ADO, the in-memory representation of data is the recordset. In ADO.net, it is the dataset A recordset looks like a to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. In ADO you cant update the database from the recordset. ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database. On order to get assembly info which namespace we should import? System.Reflection Namespace How do you declare a static variable and what is its lifetime in a dataset of 100 records? Write code. Answer1 DataSet ds1 = new DataSet(); String strCon = ”data source = IBM-6BC8A0DACEF;initial catalog = pubs;integrated security = SSPI;persist” +” security info = False;user id = sa;workstation id = IBM-6BC8A0DACEF;packet size = 4096?; String strCom1 = ”SELECT * FROM employee”; SqlDataAdapter sqlDa1 = new SqlDataAdapter(strCom1, strCon); ds1.Tables.Add(”employee”); sqlDa1.Fill(ds1, 40, 50, ds1
Help me. . . . . . hi all, i just want to say that actually i am new to asp.net 2.0 i have a work over my head and really m not knowing how form will open with already filled details of that employee and he / she can edit data from the button in the form. then he will move to Emptechexp form where all 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
Migration from ASP to ASP.net How to convert ASP site to ASP.NET site using C# http: / / www.asp.net / downloads / archived-v11 / migration-assistants / asp-to-aspnet hi, ASP.NET framework is very much different from unstrucured ASP and there is no correct way to
Tracing in ASP.NET? hi all, what is tracing? how to achieve tracing in asp.net? different ways of doing tracing? thanks and regards Aman Khan hi. . Tracing in ASP.NET 2.0 Tracing is a way to monitor the execution of your ASP.NET application. You can record exception details and program flow in a way that doesn't