I have used the Stored Procedure in this sample.
Please refer this.
HTML
<form id="form1" runat="server">
<div>
Select the course
<asp:DropDownList ID="ddlCourseTypes" runat="server">
</asp:DropDownList>
<br />
Participant Name
<asp:TextBox ID="txtParticipantName" runat="server" />
<br />
<asp:Button Text="Save" OnClick="Save" runat="server" />
</div>
</form>
Namespaces
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.PopulateCourses();
}
}
private void PopulateCourses()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CourseId, CourseName FROM Courses", conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable ds = new DataTable();
da.Fill(ds);
ddlCourseTypes.DataTextField = "CourseName";
ddlCourseTypes.DataValueField = "CourseId";
ddlCourseTypes.DataSource = ds;
ddlCourseTypes.DataBind();
ddlCourseTypes.Items.Insert(0, new ListItem("Please Select", ""));
}
}
}
}
protected void Save(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("CourseAvailability", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CourseType", this.ddlCourseTypes.SelectedItem.Value);
cmd.Parameters.AddWithValue("@ParticipantName", this.txtParticipantName.Text.Trim());
conn.Open();
String message = cmd.ExecuteScalar().ToString();
conn.Close();
ScriptManager.RegisterClientScriptBlock(sender as Control, this.GetType(), "alert", "alert('" + message + "')", true);
}
}
}
Tables
CREATE TABLE [dbo].[Courses](
[CourseId] [int] IDENTITY(1,1) NOT NULL,
[CourseTotalSeat] [int] NOT NULL,
[CourseAvailabelSeat] [int] NOT NULL,
[CourseName] [varchar](50) NOT NULL
) ON [PRIMARY]
GO
INSERT INTO [Courses]
([CourseTotalSeat]
,[CourseAvailabelSeat]
,[CourseName])
VALUES
(4
,4
,'IT')
GO
INSERT INTO [Courses]
([CourseTotalSeat]
,[CourseAvailabelSeat]
,[CourseName])
VALUES
(3
,3
,'CS')
GO
CREATE TABLE [dbo].[Participants](
[ParticipantId] [int] IDENTITY(1,1) NOT NULL,
[CourseId] [int] NOT NULL,
[ParticipantName] [varchar](50) NOT NULL
) ON [PRIMARY]
GO
Stored Procedure
-- CourseAvailability 1,'Amir Shaikh'
CREATE PROCEDURE CourseAvailability
@CourseType INT,
@ParticipantName VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SeatCount INT
SET @SeatCount = (SELECT CourseAvailabelSeat
FROM Courses
WHERE CourseId = @CourseType)
IF @SeatCount <> 0
BEGIN
INSERT INTO [Participants]([CourseId]
,[ParticipantName])
VALUES (@CourseType
,@ParticipantName)
UPDATE [Courses] SET [CourseAvailabelSeat] = [CourseAvailabelSeat] - 1
WHERE CourseId = @CourseType
SELECT 'Data Inserted'
END
ELSE
SELECT 'Seats are full'
END
GO