inserting data from SQL Server using C# in ASP.NET

Status
Not open for further replies.

garv84

Broken In
We have to insert data into Sql server from the form of Asp.net using C Sharp.can neone help me in this respect !!! I need the code basically..
 
Whats the problem dude? Forllow these steps :-

1. Create a web for with required fields as textboxes or whatever and a button to submit it.

For Example :

Code:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "*www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="*www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Panel runat ="server" ID="panel1">
    <asp:label ID="label1" runat="server" Font-Size="XX-Large">Data Entry Form</asp:label><br /><br />
        Sno : <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /><br />
        Name : <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /><br />
        Age : <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br /><br />
        Salary<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br /><br />
        <asp:Button ID="Button1" runat="server" Text="Insert Record" />
     </asp:Panel>
        </div>
    </form>
</body>
</html>

2. in the code behind, insert a using System.Data.SqlClient; statement.

Following is a generic code for inserting data:

Code:
protected void Button1_Click(object sender, EventArgs e)
    {
        SqlDataAdapter da = new SqlDataAdapter("Select * from Emp", "Server=sumitslaptop\\sqlexpress; database=Practice; integrated security=true;");
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        DataSet ds = new DataSet();
        da.FillSchema(ds, SchemaType.Source);
        DataRow dr = ds.Tables[0].NewRow();
        dr[0] = int.Parse(TextBox1.Text);
        dr[1] = TextBox2.Text;
        dr[2] = int.Parse(TextBox3.Text);
        dr[3] = double.Parse(TextBox4.Text);
        ds.Tables[0].Rows.Add(dr);
        try
        {
            da.Update(ds);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            return;
        }
        Response.Write("Record Added.");
    }

Remember to change the connection string according to your computer. Also the code will vary according to the database schema. The given code is designed for following table :

Code:
create table Emp
(
Sno int,
Name varchar(50),
Age int,
Salary money
);

And do refer to your books dude, its very basic stuff. If you need one, i'll recommend
Apress Pro ASP.NET 2.0 with C# 2005
for ASP.NET 2.0.
 
Status
Not open for further replies.
Top Bottom