In: Computer Science
Create a new website using C# & ASP.Net in Visual Studio:
1. Create a web page to access a database and display the data from a table by providing an SQL statement. Create the page with these requirements:
create label, textbox and button
the textbox will capture the SQL statement
the button will process the statement and
display the results
2. Add necessary data access pages to your project.
3. Display the data in Gridview
//Create Asp.net web application in Visual Studio and create an empty web application.
//Add database to ASP.NET project
By right-clicking on structure in solution explorer => Add -> new Item -> data -> sql database (.mdf)
Now go to table folder -> right click -> add new Table --> design table.
Now right click on Table (StudentData) and select show table data -> add new data into it.
Save the table and close it.
Now add a webform
//Design form using toolbox.
//Webform1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="data_access.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Enter Query:
"></asp:Label>
<asp:TextBox ID="txtQuery" runat="server"
Width="396px"></asp:TextBox>
<asp:Button ID="btnRunQuery" runat="server"
OnClick="btnRunQuery_Click" Text="Run" />
<br />
<asp:GridView ID="grdViewData" runat="server">
</asp:GridView>
<br />
</div>
</form>
</body>
</html>
//=====================================
Now double click on run button -> Create a on click event (event name depends on whatever id you have given to button)
//===============================
Note:--> you can get the connection string by right clicking student.mdf in solution explorer, which will be passed into SqlConnection.
//Webform1.aspx.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace data_access
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection connection = null;
protected void Page_Load(object sender, EventArgs e)
{
connection = new SqlConnection(@"Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\student.mdf;Integrated
Security=True");
connection.Open();
}
protected void btnRunQuery_Click(object sender, EventArgs
e)
{
string query = txtQuery.Text;
SqlCommand cmd = new SqlCommand(query,connection);
SqlDataAdapter sqlData = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlData.Fill(ds);
grdViewData.DataSource = ds.Tables[0];
grdViewData.DataBind();
connection.Close();
}
}
}
//Output
//If you need any help regarding this solution ........ please leave a comment ....... thanks