Solved

Insert data into SQL database

Posted on 2006-11-14
10
201 Views
Last Modified: 2008-01-09
Hi everyone,

              I have a web entry form which I have made using DetailsView in C#. I don't know how would I insert the data filled in by the data entry person to the Sql Database. Do I need to create an empty table with just the column names? How would I actually insert the entries into the respective columns in the database? There is a submit button that would enter the values in the database. Could somebody help me on this? This is very urgent.

Thank you all in advance.
0
Comment
Question by:siddhuoops
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 3
10 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 17940919
Are you binding your DetailsView to any kind of DataSource ?
0
 

Author Comment

by:siddhuoops
ID: 17940984
The DetailsView is binded to the SqlDataSource..
Here is an example of my project:

Date       TxtDate

Vendor    txtVendor

Client      ddrClient



Submit
0
 

Author Comment

by:siddhuoops
ID: 17941174
The submit button is not inside the detailsview. Its outside and all the entries are made inside the detailsview.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:siddhuoops
ID: 17942329
Here is what I have done so far but I am not getting it to work.

protected void  DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
    string fetch;

    fetch = "INSERT INTO Discrepancy(";
    fetch += "Date_To_Media, Vendor, Vendor_Name, ";
    fetch += "Client, Dealer_Agent, Invoice_Num, Invoice_Date, Invoice_Amt, Date_Given_to_Buyer, Buyer_Name, Date_Given_to_Acctg)";
    fetch += "VALUES ('";
    fetch += txtDate.Text + "','";
    fetch += txtVcode.Text + "','";
    fetch += txtVname.Text + "','";
    fetch += txtDealer.Text + "',";
    fetch += txtInvNum.Text + "','";
    fetch += txtInvDate.Text + "','";
    fetch += txtInvAmt.Text + "','";
    fetch += txtDatetoBuyer.Text + "','";
    fetch += txtDatetoAcctg.Text + "')";

    string con = "Data Source=sasql01;Initial Catalog=Projections; User ID=sa_sql;Password=str@teg1K@m3r1ka";
    SqlConnection conn = new SqlConnection(con);
    SqlCommand cmd = new SqlCommand(fetch, conn);
    int added = 0;
    try
    {
        conn.Open();
        added = cmd.ExecuteNonQuery();
        Label1.Text = added.ToString() + "records inserted.";
    }
    catch (Exception err)
    {
        Label1.Text = "Error inserting record.";
        Label1.Text += err.Message;
    }
    finally
    {

        conn.Close();
    }

}

protected void btnSubmit_Click(object sender, DetailsViewPageEventArgs e)
    {
     }

   Error: txtDate is not defined, txtVcode is not defined.................and so on.

Am I using the right function to insert my values. On the other hand, my source code looks something like this.

<%@ Page Language="C#" MasterPageFile="~/Test.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataKeyNames="Client" AllowPaging="True" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None"
       DataSourceID="SqlDataSource1" EnableViewState="False" OnPageIndexChanging="DetailsView1_PageIndexChanging">
     <Fields>
         <asp:TemplateField HeaderText="Medium">
            <ItemTemplate><asp:RadioButton ID="radPrint" runat="server" Text="Print" Width="66px" OnCheckedChanged="radPrint_CheckedChanged" GroupName="Medium" />    <asp:RadioButton ID="radBroadCast" runat="server" Text="BroadCast" GroupName="Medium" /><br />
            </ItemTemplate>
         </asp:TemplateField>
     <asp:TemplateField HeaderText="Date To Media" InsertVisible="False"
        SortExpression="Date To Media">
        <ItemTemplate>
          <asp:TextBox ID="txtDate" runat="server" Width="100px">
          </asp:TextBox>
        </ItemTemplate>
        </asp:TemplateField>
       <asp:TemplateField HeaderText="Vendor Code" SortExpression="Vendor Code">
         <ItemTemplate>
           <asp:TextBox ID="txtVcode" runat="server" Width="60px">
           </asp:TextBox>
         </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Vendor" SortExpression="Vendor">
       <ItemTemplate>
         <asp:TextBox ID="txtVname" runat="server">
         </asp:TextBox>
       </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Client">
         <ItemTemplate>
           <asp:DropDownList ID="ddrClient" DataSourceID="SqlDataSource1" DataTextField="Client"
            DataValueField="Client" AutoPostBack="True" Width="200px" runat="server">
            </asp:DropDownList>
              <asp:SqlDataSource ID="SqlDataSource1" runat="Server" ConnectionString="<%$ ConnectionStrings:ProjectionsConnectionString %>"
                SelectCommand="SELECT [Client] FROM [tbl_Current_Year_Projections]"></asp:SqlDataSource>
         </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Dealer/Agent">
          <ItemTemplate>
              <asp:TextBox ID="txtDealer" runat="server">
              </asp:TextBox>
          </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Invoice#">
         <ItemTemplate>
            <asp:TextBox ID="txtInvNum" runat="server" Width="100px">
            </asp:TextBox>
         </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Invoice Date">
         <ItemTemplate>
            <asp:TextBox ID="txtInvDate" runat="server" Width="100px">
            </asp:TextBox>
         </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Invoice Amt">
          <ItemTemplate>
             <asp:TextBox ID="txtInvAmt" runat="Server" Width="100px">
             </asp:TextBox>
          </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Date Given to Buyer">
         <ItemTemplate>
            <asp:TextBox ID="txtDatetoBuyer" runat="server" Width="100px">
            </asp:TextBox>
         </ItemTemplate>      
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Buyer Name">
            <ItemTemplate>
                <asp:DropDownList ID="ddrBuyer" AutoPostBack="true" runat="server" Width="200px">
                </asp:DropDownList>
            </ItemTemplate>
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="Date Given to acctg">
            <ItemTemplate>
                <asp:TextBox ID="txtDatetoAcctg" runat="server" Width="100px">
                </asp:TextBox>
            </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="Completed">
            <ItemTemplate>
               <asp:CheckBox ID="chkCompleted" runat="Server" />
            </ItemTemplate>
         </asp:TemplateField>
         <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
         
     </Fields>
        <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
        <EditRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
        <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
    </asp:DetailsView>
    &nbsp;
    <asp:Label ID="Label1" runat="server" Width="278px"></asp:Label><br />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectionsConnectionString %>"
        SelectCommand="SELECT [Client] FROM [tbl_Current_Year_Projections]"></asp:SqlDataSource>
    &nbsp; &nbsp;&nbsp;<br />
    &nbsp;<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit"
        Width="86px" />
    </asp:Content>
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 17943038
First of all you should use a StringBuilder for building your query rather than a string because the CLR has to allocate memory for a new string object everytime you append to it which is very slow.

Because you are using a GridView you need to use the FindControl method of the GridView to gain access to the controls (this may be a little different in 1.1 so you may need to tweak it a little).

    StringBuilder fetch = new StringBuilder();

    fetch.Append("INSERT INTO Discrepancy(");
    fetch.Append("Date_To_Media, Vendor, Vendor_Name, ");
    fetch.Append("Client, Dealer_Agent, Invoice_Num, Invoice_Date, Invoice_Amt, Date_Given_to_Buyer, Buyer_Name, Date_Given_to_Acctg)");
    fetch.Append("VALUES ('");
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtDate")).Text);
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtVcode")).Text);
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtVname")).Text);
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtDealer")).Text);
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtInvNum")).Text);
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtInvDate")).Text);
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtInvAmt")).Text);
    fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtDatetoBuyer")).Text);
    fetch.AppendFormat("{0}',')", ((TextBox)DetailsView1.FindControl("txtDatetoAcctg")).Text);

    string con = "Data Source=sasql01;Initial Catalog=Projections; User ID=sa_sql;Password=str@teg1K@m3r1ka";
    SqlConnection conn = new SqlConnection(con);
    SqlCommand cmd = new SqlCommand(fetch.ToString(), conn);

    // rest of your code here


Note that there is not error checking for the FindControl part. Ordinarily you would store the variable and check for null rather than assuming it is going to find the control, but you are obviously free to add that in if you want to.
0
 

Author Comment

by:siddhuoops
ID: 17943257
Thank you for your help. I am off tomorrow, so I will have to wait until Thursday to run this code. I will let you know by Thursday. Thank you for your help once again.
0
 

Author Comment

by:siddhuoops
ID: 17956965
I used the above code and I got an error. The error is "The type or namespace name stringBuilder' could not be found(are you missing a using directive or an assembly reference?)"
0
 

Author Comment

by:siddhuoops
ID: 17957236
I figured this error out by having Using.System.Text. But here is the problem I am running into.

I have a try catch block to check if I have any errors and this is what I am getting after I hit the submit button.
Error inserting record.Unclosed quotation mark after the character string ')'. Incorrect syntax near ')'.

This is my code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Text;


public partial class Default3 : System.Web.UI.Page
    {
    //private DataSet ds;
    //private SubmitEntry ser = new SubmitEntry();
    //private static DateTime DateToMedia=0;
    //private static int Venor=0;
    //private static string VendorName=0;
    //private static string Client=0;
    //private static string DealerAgent=0;
    //private static int InvoiceNum=0;
    //private static DateTime InvoiceDate = 0;
    //private static Decimal InvoiceAmt = 0;
    //private static DateTime DateGivenToBuyer = 0;
    //private static string BuyerName = 0;
    //private static DateTime DateGivenToAcctg = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void radPrint_CheckedChanged(object sender, EventArgs e)
    {
    }
    protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
    {

    }

   protected void btnSubmit_Click(object sender, EventArgs e)
    {
        StringBuilder fetch = new StringBuilder();

        fetch.Append("INSERT INTO Discrepancy(");
        fetch.Append("Date_To_Media, Vendor, Vendor_Name, ");
        fetch.Append("Client, Dealer_Agent, Invoice_Num, Invoice_Date, Invoice_Amt, Date_Given_to_Buyer, Buyer_Name, Date_Given_to_Acctg)");
        fetch.Append("VALUES ('");
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtDate")).Text);
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtVcode")).Text);
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtVname")).Text);
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtDealer")).Text);
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtInvNum")).Text);
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtInvDate")).Text);
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtInvAmt")).Text);
        fetch.AppendFormat("{0}','", ((TextBox)DetailsView1.FindControl("txtDatetoBuyer")).Text);
        fetch.AppendFormat("{0}',')", ((TextBox)DetailsView1.FindControl("txtDatetoAcctg")).Text);

        string con = "Data Source=sasql01;Initial Catalog=Projections; User ID=sa_sql;Password=str@teg1K@m3r1ka";
        SqlConnection conn = new SqlConnection(con);
        SqlCommand cmd = new SqlCommand(fetch.ToString(), conn);


        //Add the parameters
        //cmd.Parameters.AddWithValue("@Date_To_Media",
        int added = 0;
        try
        {
            conn.Open();
            added = cmd.ExecuteNonQuery();
            Label1.Text = added.ToString() + "records inserted.";
        }
        catch (Exception err)
        {
            Label1.Text = "Error inserting record.";
            Label1.Text += err.Message;
        }
        finally
        {

            conn.Close();
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
    }
}
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 17958218
Slight typo. The line:

    fetch.AppendFormat("{0}',')", ((TextBox)DetailsView1.FindControl("txtDatetoAcctg")).Text);

Should say:

    fetch.AppendFormat("{0}')", ((TextBox)DetailsView1.FindControl("txtDatetoAcctg")).Text);
0
 

Author Comment

by:siddhuoops
ID: 17958829
got it to work..great!! thanks a lot.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

628 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question