Submit Form to insert data into SQL and display with a gridview (edit as well) below how do i insert data into sql table?

I have an asp.net page that has a simple form where a user can submit customers information. Below that I have a gridview which displays customer information submited by the user who is logged in. I have the gridview displaying, sorting and updating as I want however I can't figure out how to bind a button click to insert data into the customer table and then have it refresh the gridview when they submit. Here is the basic code; (I am using AJAX for a calendar when a user wants to edit an appointment date) 

<div class="leftBar">
    <div align=center>
    Submit New Customer</div><br />
      <table><tr><td>First Name</td><td>Last Name</td></tr>
  <tr><td><asp:TextBox ID="cfirst_name" runat="server"></asp:TextBox></td>
  <td><asp:TextBox ID="clast_name" runat="server"></asp:TextBox><br /></td></tr>
  <tr><td>Cell Phone </td><td>Other Phone</td></tr>
  <tr><td><asp:TextBox ID="ccell_phone" runat="server"></asp:TextBox></td>
  <td><asp:TextBox ID="cother_phone" runat="server"></asp:TextBox></td></tr>  
  <tr><td>Email</td><td>Appt. Date</td></tr>
  <tr><td><asp:TextBox ID="cemail" runat="server" Height="22px" Width="128px"></asp:TextBox></td>
  <td><asp:TextBox ID="cappt_date" runat="server" Height="22px"></asp:TextBox></td></tr>
  <tr><td>Notes:</td></tr>
  <tr><td><asp:TextBox Rows="3" ID="cnotes" runat="server" Height="52px"></asp:TextBox></td>
   <td colspan="2"><div align=center id="submit">
    <asp:Button ID="Button1" runat="server" Text="Submit" /></div></td></tr>
    </table>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager> 
</div>


 <br /><br />
<asp:SqlDataSource ID="jras_intranet" runat="server" 
    ConnectionString="<%$ ConnectionStrings:JRAS_IntranetConnectionString %>" 
    
        SelectCommand="SELECT [first_name], [last_name], [bd_id], [userid], [location_code], [date_enrolled], [w9_complete], [cell_phone] FROM [referral_members]">
</asp:SqlDataSource>
    <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" 
        DeleteMethod="Delete" InsertMethod="Insert" 
        OldValuesParameterFormatString="original_{0}" SelectMethod="GetDataCustomerEntries" 
        TypeName="customer_entryTableAdapters.customer_entryTableAdapter" 
        UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_cus_id" Type="Int32" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="bd_id" Type="Int32" />
            <asp:Parameter Name="first_name" Type="String" />
            <asp:Parameter Name="last_name" Type="String" />
            <asp:Parameter Name="cell_phone" Type="String" />
            <asp:Parameter Name="other_phone" Type="String" />
            <asp:Parameter Name="status" Type="String" />
            <asp:Parameter Name="paid" Type="String" />
            <asp:Parameter Name="date_submited" Type="DateTime" />
            <asp:Parameter Name="notes" Type="String" />
            <asp:Parameter Name="email" Type="String" />
            <asp:Parameter Name="location" Type="String" />
            <asp:Parameter Name="appointment_date" Type="String" />
            <asp:Parameter Name="Original_cus_id" Type="Int32" />
        </UpdateParameters>
        <InsertParameters>
            <asp:Parameter Name="bd_id" Type="Int32" />
            <asp:Parameter Name="first_name" Type="String" />
            <asp:Parameter Name="last_name" Type="String" />
            <asp:Parameter Name="cell_phone" Type="String" />
            <asp:Parameter Name="other_phone" Type="String" />
            <asp:Parameter Name="status" Type="String" />
            <asp:Parameter Name="paid" Type="String" />
            <asp:Parameter Name="date_submited" Type="DateTime" />
            <asp:Parameter Name="notes" Type="String" />
            <asp:Parameter Name="email" Type="String" />
            <asp:Parameter Name="location" Type="String" />
            <asp:Parameter Name="appointment_date" Type="String" />
        </InsertParameters>
    </asp:ObjectDataSource>
    
      <asp:GridView ID="GridView1" 
    runat="server" 
    AllowPaging="True" 
        AllowSorting="True" 
        DataKeyNames="cus_id"
        DataSourceID="ObjectDataSource2" 
        CellPadding="4" ForeColor="#333333"
        CssClass="gridview" 
        PageSize="5" AutoGenerateColumns="False" Font-Size="Medium" >
        <RowStyle BackColor="#EFF3FB" />
        <Columns>
        <asp:CommandField ShowEditButton="True" />
               <asp:TemplateField HeaderText="Date Submited" 
                SortExpression="appointment_date">
             <ItemTemplate><%#Eval("date_submited", "{0:M/dd/yyyy}")%>
             </ItemTemplate>
             </asp:TemplateField>  
     <asp:TemplateField SortExpression="first_name" HeaderText="First Name">
    <ItemTemplate><%#Eval("first_name")%></ItemTemplate>
    <EditItemTemplate><asp:Label id="first_name" Font-Bold=true runat="server" Text='<%# Eval("first_name") %>' />
    </EditItemTemplate>  
      </asp:TemplateField> 
   <asp:TemplateField SortExpression="last_name" HeaderText="Last Name">
   <ItemTemplate><%#Eval("last_name")%></ItemTemplate>
    <EditItemTemplate><asp:Label id="last_name" Font-Bold=true runat="server" Text='<%# Eval("last_name") %>' />
    </EditItemTemplate>  
       </asp:TemplateField> 
   <asp:BoundField DataField="cell_phone" HeaderText="Cell#" 
                SortExpression="cell_phone" />
     <asp:TemplateField SortExpression="email" HeaderText="Email">
    <ItemTemplate><%#Eval("email")%></ItemTemplate>
    <EditItemTemplate><asp:TextBox id="email" runat="server" Columns="20" Text='<%# Bind("email") %>'></asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateField>   
      <asp:BoundField DataField="status" HeaderText="Status"
                SortExpression="status" ReadOnly=true />
            <asp:BoundField DataField="paid" HeaderText="Paid"
                SortExpression="paid" ReadOnly=true />
            <asp:TemplateField HeaderText="Appointment Date" 
                SortExpression="appointment_date">
             <ItemTemplate><%#Eval("appointment_date", "{0:M/dd/yyyy}")%>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:TextBox runat="server" id="textbox1" Text='<%# Bind("appointment_date") %>'></asp:TextBox>
             <cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="textbox1" PopupButtonID="textbox1"></cc1:CalendarExtender>
             </EditItemTemplate>
             </asp:TemplateField>

           </Columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
 

 

Please give me some direction here. I am of course new to .net and visual studio. I have experience with HTML and Asp classic.

Best regards,

Shawn

0
shawn
4/25/2009 6:36:13 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

6 Replies
1914 Views

Similar Articles

[PageSpeed] 29

This uses a formview to submit the info and displays the submitted info in a gridview. 

 

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:AccreditationConnection %>" 
    InsertCommand="INSERT INTO [Contact] ([Text], [CodeId]) VALUES (@Text, @CodeId)" 
    SelectCommand="SELECT [ID], [FirstName], [LastName], , [CodeId], [Text] FROM [Contact]" >
    <InsertParameters>
        <asp:Parameter Name="Text" Type="String" />
        <asp:Parameter Name="CodeId" Type="Int32" />
    </InsertParameters>
</asp:SqlDataSource>
<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" 
    DataSourceID="SqlDataSource1" DefaultMode="Insert">
    <InsertItemTemplate>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
            ConnectionString="<%$ ConnectionStrings:AccreditationConnection %>" 
            SelectCommand="SELECT [ID], [Name] FROM [Code] ORDER BY [Name]">
        </asp:SqlDataSource>
        Code: <asp:DropDownList ID="DropDownList1" runat="server" 
            DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="ID" 
            SelectedValue='<%# Bind("CodeId") %>'>
        </asp:DropDownList>
        <br />
        Text:
        <asp:TextBox ID="TextTextBox" runat="server" Text='<%# Bind("Text") %>' />
        <br />
        <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
            CommandName="Insert" Text="Insert" />
         <asp:LinkButton ID="InsertCancelButton" runat="server" 
            CausesValidation="False" CommandName="Cancel" Text="Cancel" />
    </InsertItemTemplate>
</asp:FormView>
<asp:GridView ID="GridView1" runat="server" 
    DataSourceID="SqlDataSource1" 
    AutoGenerateColumns="False" 
    DataKeyNames="ID">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
        <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
        <asp:BoundField DataField="CodeId" HeaderText="CodeId" SortExpression="CodeId" />
        <asp:BoundField DataField="Text" HeaderText="Text" SortExpression="Text" />
    </Columns>
    <EmptyDataTemplate>
        No data returned
    </EmptyDataTemplate>
</asp:GridView>
If your gridview doesn't refresh with the new data you will have to add an event in the code behind that rebinds the gridview:     
Private Sub FormView1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) Handles FormView1.ItemInserted GridView1.DataBind() End Sub 
View Brenden Kehren's profile on LinkedIn
Remember to mark as answer if this post answered your question.
0
b471code3
4/25/2009 9:24:15 PM

Thank you! Works great. I have another simple question. how do you pass hidden values to the insert statement? Can you give me an example? I want something like this from HTML;

<input type="hidden" id="submit_date" value="&now()&" name="submitdate" />

Basically using ASP classic and HTML this will pass on submit and then I would bind it like;

submit_date = request.form("submitdate")

now I would use that variable in my insert statment;

sql_insert = "INSERT into customer_entry submit_date VALUES ( ' "&submit_date&" ' )

So how can this be acheived with ASP.net? Sorry for the basic question but I appreciate your help.

0
shawn
4/26/2009 2:35:39 AM

Yes there is a hidden field control for asp.net and the insert would be very similar to how I mention above with the exception of changing the control id.


View Brenden Kehren's profile on LinkedIn
Remember to mark as answer if this post answered your question.
0
b471code3
4/26/2009 3:03:15 AM

Okay so something like;

 

<asp:HiddenField ID="HiddenField1" runat="server" value=Today()/>

 ? I guess I am just confused on how to input the right format for Todays date in the hidden field and then how do I reference it for the Insert statement?

I would think by the ID, INSERT into customers_entry date_submited VALUES (@hiddenField1)

Does this look right? TY!!

0
shawn
4/26/2009 3:44:18 AM

Is it always going to be the current date?  If so, just set the field in SQL to default to getDate() and you won't have to fool around with it on the front end.  If not, you can set it in the when you modify the datasource in the GUI.  You will need to create an insert parameter on the datasource and make reference to it as you have shown above.


View Brenden Kehren's profile on LinkedIn
Remember to mark as answer if this post answered your question.
0
b471code3
4/26/2009 2:18:58 PM

Thank you! That should work well. I still need to know how to pass variables over though. For example when a user is logged in I want to set a session variable to their cus_id which is a primary identity key in their info table. And then insert that value into another table so I can link them later. So something like

session("cus_id") = Rs("cus_id")

INSERT into customer_entry
cus_id
VALUES
(' "&session("cus_id")&" ')

I guess my question is can I insert session variables the same way I would in asp classic? Is there a way to make session variables easier in Visual Studio 2008?

Please forgive me for being a beginner. I am a quick learner and will pick this up quickly once I figure out the main differences.

One last question if you have the time; I want to create a login page to access a member portion of the site. I notice that VS 2008 has a login control however I want the usernames and passwords from a seperate table I already have and if they are logged in correctly I want to redirect them to another page which checks that they are logged in before loading it. I've done this in asp classic using session variables to check they are logged in before loading the page like;

THIS IS THE LOGIN PAGE
 

If request.form("username") <> "" Then
  If request.form("password") <> "" Then
username = replace(request.form("username"), "'", "")
username = replace(request.form("username"), ";", "")
password = replace(request.form("password"), "'", "")
username = replace(request.form("username"), ";","")
SQL_select = "Select * from users WHERE username=' "&username&" ' AND password=' "&password&" ' ;
set rs=dataconn.execute(sql_select)  
If not rs.eof Then
session("userloggedin") = True
response.redirect("managerpage.asp")
Else
response.write("Invalid Login")
session.abandon
End If
rs.close
Set sql_select = NOTHING
Set rs = NOTHING
username = ""
password = ""
 

THIS IS THE MANAGER PAGE
 
If not session("userloggedin") Then
response.redirect("login.asp")
End If 

' Process page info here
 I can repost this and start a new thread or do some more searching if you are too busy to answer. Thank you so far!!
0
shawn
4/27/2009 1:42:30 PM
Reply:

Similar Artilces:

Data Controls insert rows into gridview then insert rows from gridview into SQL Table
Hello there, I'm still new at performing miracles with code . Currently I am having trouble with my latest coding adventure I have a web application which records jobs and labour assigned to jobs. The issue in particular I'm having is the way in which labour is to be assigned. I want to use standard controls (Textbox, Dropdownlist) to record the values into a gridview (ie,put multiple rows into the gridview using the controls). Then, when all the inserting is complete, the user clicks a submit button to insert all the rows from the gridview into a database table. The reason for...

How to insert data to Sql from gridview data?
Hi all,I am new in VB.net. I am developing a project which need to display data from Table1 on GridView (the no. of row of data read from Table1 is various every time), after user confirm the data by clicking a button, the data will insert into Table2.I am able to read data from Table1 and show it on GridView using ExecuteReader() , however, I am struggling on how to insert those data from GridView. anyone could help is appreciated. thanks in advance. Danny  you can use a "button" at every row and on clicking that button, you can write code in the gridview_rowcommand(...

how do i insert data into sql server using data from textboxes and sql connection and sql command
anyone can give me a simple explaination and code.. Thanx in advance Take a look @ Sample Code: How to add...Sushila Bowalekar PatelVisual ASP/ASP.NET MVPhttp://weblogs.asp.net/sushilasb There are a lot of tutorials out there, but I know they can be a bit confusing as they all approach things slightly differently. Basically a nice simple version would go like this:' *** First set up your connectionDim conConnection As New SqlConnection("server=servername;database=yourdatabase;uid=yourname;pwd=yourpassword;")' *** This line takes care of your sommand text and command connection in one ...

Re: How to insert data to Sql from gridview data?
Hi,I have been Googling all afternoon but I'm struggling to code the button click event to write an email address to an SQL server database! I am using a Textbox for the user to enter their email address and a Button to 'insert' the entry into the db. I have set up a SQLDataSource called 'Subscribe' and have entered the correct INSERT command. This works fine when I execute the SQL in Query Builder but I can't get the button to do the task from a web page. Any suggestions? 1    <%@ Page Language="VB" AutoEventWir...

Inserting Form Data to a SQL Data base
Hi Everyone!  I am very new to development and trying to put together a very simple website.  I just want one piece of functionality that I see as complicated but a devoper with 2 weeks knowledge would be able to do :)   So I'm using Web Express 2005 in VB code I have a page with 3 fields, name, email and phone number All I want is them to press Submit and the data they type in goes to the database and the system navigates to screen that says (You data has been saved(I have created this screen I just need to know how to get there))...this has been infutriating me as...

is there an sql statement to insert data to one table and getting the data from another table
Ok I have a table that have general categories with just name and CatNo. Now what I want to know is when I create a client to move all the data in general categories to another table called categories that have the clientid to associate it with the client. I would appreciate for any help what is your question here??Shravan Addaypally MCP...

I submit a form and insert data to the sql, then I want to show the thank you message, not show the form. how can I switch the form to the thank you message.
Here is my code: if (Page.IsPostBack) // form submitted {SqlConnection sc = null; SqlCommand command = null; try {sc = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSource"].ConnectionString); sc.Open();String strSQL = String.Format(@"INSERT INTO Contactus (ContactusEmail,ContactusFirstName,ContactusLastName, ContactusPhone, ContactusComments, ContactusDate) VALUES ( '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')", EmailBox.Text, FirstNameBox.Text, LastNameBox.Text, PhoneBox.Text, CommentsTextBox.Text,...

INSERT data into SQL table... TableAdapter Commands or SQL Commands? Which is best?
I've been working on some unbound data forms, and trying to decide what is best when inserting and/or updating a record into a SQL table.    I can successfully use SQL commands to insert data from VS2008 into a sql table on the server, doing something such as... Dim conn As New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName")Using conn conn.Open() Dim cmd As New SqlCommand("UPDATE tableName SET folderName = @folder WHERE id = @id", conn) cmd.Parameters.AddWithValue("@folder", txtFolder.Te...

Insert, Edit sql data via Gridview or DataList
I'm new to this area, so please treat me as a newbie.I want to display my sql database data in a tabular layout, with options to edit and add new data etc.What is the best control for this ?  I will have a few hundred rows and use paging.I have a connection and can get the Gridview control displaying data etc, but I'm a bit lost when trying to add edit and insert features, is there any good walkthru's for creating Insert/Edit Commands? and using query builder.If anyone can recommend a good book for 2005 beta 2 with walk thru's (its the way I ike it!) to get me going.thanks. HiYou can ...

need help inserting data into table with sql insert into using textbox values
the error message I get is {"Object reference not set to an instance of an object."} and it points to <  Tickr As String = CType(FindControl("TickerTextbx"), TextBox).Text >     this is my code":  Protected Sub TickMastBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TickMastBtn.Click REM Collect variablesDim Tickr As String = CType(FindControl("TickerTextbx"), TextBox).Text Dim Comp As String = CType(FindControl("CoTextbx"), TextBox).TextDim Exch As String = CType(FindControl("...

What is the best way to insert data into sql server with data from large web form?
Hi, I realized that this question was probably asked before but I could not find the answer doing the search thing.  So here is the scenario.  I have a page that has roughly about 350 form fields consisting of textboxes, radio buttons, drop down list boxes, and checkboxes controls. These fields are separated by sections and are inside panels.  My current steps are like this.  I pass a submitid and the panel to a sub that loops through the panel and find any server controls that is a textbox, radio button, drop down list box, or checkbox.  Grab the id and the val...

Inserting data in batch mode in a SQL Table using .NET
Hi, I have an ASP.NET Web Service that accepts a DataSet object passed to it. This DataSet will contain a large number of records in it's table. What I want to do (if possible) is insert all records in a SQL table in a batch mode (one go). Is this doable? Thanks,--Mazen depends on the size of the dataset.Kay LeeMySpace.com - http://www.myspace.com/kragieInfrastructure GroupMySpace.com- Code to live, but Live to code....

After submit form to insert data in SQL, need to direct to another page!!!
I have this situation that couldn't figure out how.I have generate a form that user(s) input their informations, once the submit button is press the collected data insert into the sql db, but then the same page with the same information post back again.  Is there a way to fix this problem?This is what I would like to do if it is possible.  As soon as the users input thier informations and press submit, the data is insert into the sql db and then direct them to a thank you page.Thanks,hydro couldn't you do: private void Button1_Click(object sender, System.EventArgs e){string goTo...

how to insert all data from vb.net dataset to a temporary table in sql server database
I always get solutions for my question from the forum , thanks for all your help. Question is i have select some data from a database in server 1 and save it in to a DataSet in vb.net now i need to create a temporary table in server 2 test database and insert all rows in DataSet. I know I can read row by row in DataSet.Table(0) and execute a insert statement for each row. but i think this is time consuming. Is there any way that I can transfer all data in DataSet to a temporary table at once. need your help please. I am selecting data from Server 1 Datababse (original1) as follows &n...

Web resources about - Submit Form to insert data into SQL and display with a gridview (edit as well) below how do i insert data into sql table? - asp.net.presentation-controls

GridView SelectedItem Binding Gotcha in WinRT
Last night when I was doing some WinRT hacking I was trying to setup databinding to the selected item in the GridView control and I ran into ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Advanced Search Gridview Latest News Releases All ...

CNW Group
... Services Beyond the Wire About CNW my CNW CNW Access CNW Directories Financials Webcasts Events my CNW All News Releases Advanced Search Gridview ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Add a Filter Gridview Latest News Releases All Today ...

New CmdLets of Powershell 2.0
New CmdLets of Powershell 2.0

Price Drop: Softbox
... objects- create product reflection- changing the background with something more interestingUse it as:- softbox- honeycomb softbox- gridview ...

Profile.aspx: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 25 Oct 2012

DotNetKicks.com - Upcoming stories
DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ...

View Features - ExtendASP
Call 847-681-9827 or Request a Demo View Features Testimonials Pricing About Us Coming Soon ExtendASP exposes every feature, more than any other ...

Resources last updated: 11/28/2015 11:57:33 AM