Basic codes for web application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class frmAddNotes : System.Web.UI.Page
{
string CS = ConfigurationManager.ConnectionStrings["ConstrNikoBank"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
txtAuthor.Text = Session["User"].ToString();
//lblUser.Text = Session["User"].ToString();
txtDateTime.Text = DateTime.Now.ToString();
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (txtTitle.Text == string.Empty)
{
Response.Write("<script>alert('Title cannot be blank!')</script>");
}
else if (txtDescription.Text == string.Empty)
{
Response.Write("<script>alert('Description cannot be blank!')</script>");
}
else
{
try
{
SqlConnection conn = new SqlConnection(CS);
conn.Open();
SqlCommand cmd = new SqlCommand("NOTE_INSERT", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Title", txtTitle.Text.ToUpper());
cmd.Parameters.AddWithValue("@AuthorName", txtAuthor.Text.ToUpper());
cmd.Parameters.AddWithValue("@Date", txtDateTime.Text.ToUpper());
cmd.Parameters.AddWithValue("@Description", txtDescription.Text.ToUpper());
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Note saved sucessfully!')</script>");
Cleardata();
//Response.Redirect("frmNotes.aspx");
}
catch (Exception ex)
{
Response.Write("<script>alert('Error! please check')</script>");
}
}
}
public void Cleardata()
{
txtAuthor.Text = "";
txtDateTime.Text = "";
txtDescription.Text = "";
txtTitle.Text = "";
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class frmAddNotes : System.Web.UI.Page
{
string CS = ConfigurationManager.ConnectionStrings["ConstrNikoBank"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
txtAuthor.Text = Session["User"].ToString();
//lblUser.Text = Session["User"].ToString();
txtDateTime.Text = DateTime.Now.ToString();
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (txtTitle.Text == string.Empty)
{
Response.Write("<script>alert('Title cannot be blank!')</script>");
}
else if (txtDescription.Text == string.Empty)
{
Response.Write("<script>alert('Description cannot be blank!')</script>");
}
else
{
try
{
SqlConnection conn = new SqlConnection(CS);
conn.Open();
SqlCommand cmd = new SqlCommand("NOTE_INSERT", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Title", txtTitle.Text.ToUpper());
cmd.Parameters.AddWithValue("@AuthorName", txtAuthor.Text.ToUpper());
cmd.Parameters.AddWithValue("@Date", txtDateTime.Text.ToUpper());
cmd.Parameters.AddWithValue("@Description", txtDescription.Text.ToUpper());
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Note saved sucessfully!')</script>");
Cleardata();
//Response.Redirect("frmNotes.aspx");
}
catch (Exception ex)
{
Response.Write("<script>alert('Error! please check')</script>");
}
}
}
public void Cleardata()
{
txtAuthor.Text = "";
txtDateTime.Text = "";
txtDescription.Text = "";
txtTitle.Text = "";
}
Dataset & Other Bindings
public partial class AddBranch : System.Web.UI.Page { string CS = ConfigurationManager.ConnectionStrings["LIBRA_LIBDB"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Gridfill(); } } protected void btnAddBranch_Click(object sender, EventArgs e) { try { Session["eDatetime"] = DateTime.Now.ToString(); SqlConnection conn = new SqlConnection(CS); conn.Open(); SqlCommand cmd = new SqlCommand("BRANCH_INSERT", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Subject", txtSubject.Text.ToUpper()); cmd.Parameters.AddWithValue("@BranchName", txtBranchName.Text.ToUpper()); cmd.Parameters.AddWithValue("@EntryDate", Session["eDatetime"].ToString()); cmd.ExecuteNonQuery(); conn.Close(); SqlDataAdapter da = new SqlDataAdapter("BRANCH_SELECT", conn); DataSet ds = new DataSet(); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { lblmsg.Text = "Branch added successfully!"; txtBranchName.Text = ""; txtSubject.Text = ""; GridView1.DataSource = ds; GridView1.DataBind(); } } catch (Exception ex) { lblmsg.Text = ex.Message; txtBranchName.Focus(); } } public void Gridfill() { DataSet dss = new DataSet(); SqlDataAdapter daa = new SqlDataAdapter("BRANCH_SELECT", CS); daa.Fill(dss); GridView1.DataSource = dss; GridView1.DataBind(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; Gridfill(); } protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e) { } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; Gridfill(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { try { int BranchID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value); TextBox tBranchName = GridView1.Rows[e.RowIndex].Cells[3].Controls[0] as TextBox; TextBox tSubject = GridView1.Rows[e.RowIndex].Cells[4].Controls[0] as TextBox; TextBox tEntryDate = GridView1.Rows[e.RowIndex].Cells[5].Controls[0] as TextBox; SqlConnection conn = new SqlConnection(CS); conn.Open(); SqlCommand cmd = new SqlCommand("BRANCH_UPDATE", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BranchID", BranchID); cmd.Parameters.AddWithValue("@Subject", tSubject.Text); cmd.Parameters.AddWithValue("@BranchName", tBranchName.Text); cmd.Parameters.AddWithValue("@EntryDate", tEntryDate.Text); cmd.ExecuteNonQuery(); conn.Close(); GridView1.EditIndex = -1; Gridfill(); lblmsg.Text = "Branch updated successfully!"; } catch (Exception ex) { lblmsg.Text = ex.Message; } } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { try { GridViewRow row = GridView1.Rows[e.RowIndex]; int bid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value); //int BranchID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); Session["eDatetime"] = DateTime.Now.ToString(); SqlConnection conn = new SqlConnection(CS); conn.Open(); SqlCommand cmd = new SqlCommand("BRANCH_DELETE", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BranchID", bid); cmd.ExecuteNonQuery(); conn.Close(); Gridfill(); lblmsg.Text = "Branch deleted successfully!"; } catch (Exception ex) { lblmsg.Text = ex.Message; } } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; Gridfill(); } }
Web.config File configuration
<configuration> <connectionStrings> <add name="LIBRA_LIBDB" connectionString ="Data Source=DESKTOP-D0ACK3L\LOCALSERVER;Initial Catalog=LIBRA_LIB;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <appSettings> <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/> </appSettings> </configuration>
Dropdown list fields
string CS = ConfigurationManager.ConnectionStrings["LIBRA_LIBDB"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SqlConnection conn = new SqlConnection(CS); DataSet dss = new DataSet(); SqlDataAdapter daa = new SqlDataAdapter("BRANCH_SELECT", conn); daa.Fill(dss); rdoBranchSelect.DataSource = dss; rdoBranchSelect.DataTextField = "BranchName"; rdoBranchSelect.DataValueField = "BranchID"; rdoBranchSelect.DataBind(); //rdoBranchSelect.Items.Insert(0, "----------SELECT PUBLICATION---------"); //rdoBranchSelect.DataSource = dss; //rdoBranchSelect.DataTextField = "BranchName"; //rdoBranchSelect.DataValueField = "BID"; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter("PUBLICATION_SELECT", conn); da.Fill(ds); ddlpublicationName.DataSource = ds; ddlpublicationName.DataTextField = "Publication"; ddlpublicationName.DataValueField = "PID"; ddlpublicationName.DataBind(); ddlpublicationName.Items.Insert(0, "----------SELECT PUBLICATION---------"); } }
Retrive Data Using Dataset
protected void btnlogin_Click(object sender, EventArgs e) { if (rdolibrarian.Checked == true) { SqlConnection conn = new SqlConnection(CS); conn.Open(); SqlCommand cmd = new SqlCommand("ADMIN_SELECT_FOR_LOGIN", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim()); cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim()); cmd.ExecuteNonQuery(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { Session["AID"] = ds.Tables[0].Rows[0]["aid"].ToString(); Session["User"] = txtUserName.Text; Response.Redirect("Home.aspx"); } else { lblmsg.Text = "Invalid credentials!"; txtUserName.Focus(); } conn.Close(); } else if (rdostudent.Checked == true) { SqlConnection conn = new SqlConnection(CS); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT_STUDENT_FOR_LOGIN", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Email", txtUserName.Text.Trim()); cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim()); cmd.ExecuteNonQuery(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { Session["STUDSID"] = ds.Tables[0].Rows[0]["SID"].ToString(); Session["STUDUSERNAME"] = ds.Tables[0].Rows[0]["FirstName"].ToString(); Session["STUDLASTNAME"] = ds.Tables[0].Rows[0]["LastName"].ToString(); Session["StudentPHOTO"] = ds.Tables[0].Rows[0]["Image"].ToString(); Session["User"] = txtUserName.Text; Response.Redirect("~/Student/StudentHome.aspx"); } else { lblmsg.Text = "Invalid credentials!"; txtUserName.Focus(); } conn.Close(); } else if (rdostudent.Checked || rdolibrarian.Checked == false) { lblmsg.Text = "Please select User type!"; txtUserName.Focus(); } }Retrive Data Using DataReader
private void frmChangePassword_Load(object sender, EventArgs e) { conn = new SqlConnection(CS); conn.Open(); txtanswer.Focus(); cmd = new SqlCommand("select username from tempuser", conn); dr = cmd.ExecuteReader(); if (dr.Read()) { txtusername.Text = dr[0].ToString(); } dr.Close(); //display value in textbox cmd = new SqlCommand("select question,answer from Users where username='" + txtusername.Text + "'", conn); dr = cmd.ExecuteReader(); while (dr.Read()) { lblquestion.Text = dr[0].ToString(); ans = dr[1].ToString(); } dr.Close(); }
Parameterized Updated command
private void btnreset_Click(object sender, EventArgs e) { conn = new SqlConnection(CS); conn.Open(); if (txtpass.Text != string.Empty || txtconfpass.Text != string.Empty) { if (txtpass.Text.Length >= 8) { if (txtpass.Text == txtconfpass.Text) { cmd = new SqlCommand("update Users set password=@pass where username=@user", conn); cmd.Parameters.AddWithValue("user", txtusername.Text); cmd.Parameters.AddWithValue("pass", txtpass.Text); cmd.ExecuteNonQuery(); MessageBox.Show("Password Sucessfully Changed", "Sucessfull", MessageBoxButtons.OK, MessageBoxIcon.Information); txtconfpass.Clear(); txtpass.Clear(); txtanswer.Clear(); txtusername.Clear(); this.Size = new Size(634, 480); } else { MessageBox.Show("Both Password Must Be Same!"); } }
Update Command Using Store Procedure
USE[Student] GO /****** Object: StoredProcedure [dbo].[UPDATE_STUDENT] Script Date: 6/12/2023 11:17:42 AM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE[dbo].[UPDATE_STUDENT] ( @Name nvarchar(50), @Age int, @Gender nvarchar(50), @Contact nvarchar(50), @Email nvarchar(50), @ID int ) AS SET NOCOUNT OFF; UPDATE[tblStudent] SET[Name] = @Name, [Age] = @Age, [Gender] = @Gender, [Contact] = @Contact, [Email] = @Email WHERE(([ID] = @ID)); SELECT ID, Name, Age, Gender, Contact, Email FROM tblStudent WHERE(ID = @ID)
Simple DataFirst Aproch ASP.NT MVC 5
using SimpleDBfirstFE.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SimpleDBfirstFE.Controllers
{
public class HomeController : Controller
{
DatabaseFirstEFEntities db = new DatabaseFirstEFEntities();
// GET: Home
public ActionResult Index()
{
var data = db.Students.ToList();
return View(data);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Student s)
{
if (ModelState.IsValid == true)
{
db.Students.Add(s);
int a = db.SaveChanges();
if (a > 0)
{
TempData["InsertMessge"] = "<script>alert('Student Added Successfully!')</script>";
return RedirectToAction("Index");
}
else
{
TempData["InsertMessge"] = "<script>alert('Data couldn't be added!')</script>";
}
}
else
{
TempData["InsertMessge"] = "<script>alert('Please check the data!')</script>";
}
return View();
}
public ActionResult Edit(int ID)
{
var row = db.Students.Where(model => model.ID == ID).FirstOrDefault();
return View(row);
}
[HttpPost] // for save button
public ActionResult Edit(Student s)
{
db.Entry(s).State = EntityState.Modified;
int a = db.SaveChanges();
if (a > 0)
{
TempData["UpdateMessge"] = "<script>alert('Data updated Successfully!')</script>";
return RedirectToAction("Index");
}
else
{
TempData["UpdateMessge"] = "<script>alert('Data coudn't updated please check!')</script>";
}
return View(s);
}
public ActionResult Delete(int ID)
{
var DeletedRow = db.Students.Where(model => model.ID == ID).FirstOrDefault();
return View(DeletedRow);
}
[HttpPost]
public ActionResult Delete(Student s)
{
db.Entry(s).State = EntityState.Deleted;
int a = db.SaveChanges();
if (a > 0)
{
TempData["DeleteMessge"] = "<script>alert('Data deleted Successfully!')</script>";
return RedirectToAction("Index");
}
else
{
TempData["DeleteMessge"] = "<script>alert('Data coudn't deleted please check!')</script>";
}
return View(s);
}
public ActionResult Details(int ID)
{
var Detailsrow = db.Students.Where(model => model.ID == ID).FirstOrDefault();
return View(Detailsrow);
}
}
}Response.Write("<script language='javascript'>window.alert('Student registraion successfully done!, You are being redirected to Login!');window.location='frmLogin.aspx';</script>");//Response.Write("<script>alert('Student registraion successfully done!')</script>");//Response.Redirect("frmLogin.aspx");ClearData();Brouws File
Private Sub CommandButton1_Click() Dim files Dim FildialogueOpen As Office.FileDialog Set FildialogueOpen = Application.FileDialog(msoFileDialogOpen) FildialogueOpen.Show files = FildialogueOpen.SelectedItems(1) If files = "" Then MsgBox "File not selected!" Exit Sub Else Workbooks.Open (files) End If End Sub
No comments:
Post a Comment