Saturday, December 25, 2021

WinForm ComboBox CRUD Operations With SQLServer Part 5 in Hindi

WinForm ComboBox

CRUD Operations Series

CODE:


ALTER TABLE tbl_Employee
ADD Designation NVARCHAR(50) null, JobCategory nvarchar(50) null

CODE:


ALTER PROCEDURE [dbo].[usp_AddEmployee]
(
@FirstName 		NVARCHAR(50),
@LastName 		NVARCHAR(50),
@Email			NVARCHAR(50),
@IsVB			BIT,
@IsJava			BIT,
@IsCSharp		BIT,
@Gender			INT,
@Dob			DATETIME = null ,
@Tob			DATETIME = null,
@Designation	NVARCHAR(50),
@JobCategory	NVARCHAR(50)
)
As
BEGIN
INSERT INTO [dbo].[tbl_Employee]([FirstName],[LastName],[Email],[IsVB],[IsJava],
[IsCSharp],[Gender],[DOB],[TOB],[Designation],[JobCategory])
VALUES (@FirstName, @LastName , @Email, @IsVB, @IsJava, @IsCSharp, @Gender, @Dob, 
@Tob, @Designation,@JobCategory)
END

Add another table to manage list items of different ComboBox

CODE:


CREATE TABLE tbl_List(
ListId int primary key identity(1,1) not null,
Description nvarchar(50) not null,
ListType INT not null
)

CODE:


INSERT INTO tbl_List(Description, ListType)
VALUES( 'Software Developer', 1);
INSERT INTO tbl_List(Description, ListType)
VALUES( 'Sr. Software Developer', 1);
INSERT INTO tbl_List (Description, ListType)
VALUES( 'Team Lead', 1);
INSERT INTO tbl_List(Description, ListType)
VALUES( 'Project Manager', 1);
INSERT INTO tbl_List(Description, ListType)
VALUES( 'Contract', 2);
INSERT INTO tbl_List(Description, ListType)
VALUES( 'Part-time', 2);
INSERT INTO tbl_List (Description, ListType)
VALUES( 'Permanent', 2);

Stored procedure

CODE:


CREATE PROCEDURE [dbo].[usp_ListItems]
(
@ListType	INT
)
As
BEGIN
SELECT * FROM [dbo].[tbl_List]
WHERE [ListType] = @ListType;
END

Form Load Event will manage the list items of the ComboBox controls

CODE:


        private void EmployeeForm_Load(object sender, EventArgs e)
        {
            //Designation
            DesignationComboBox.DataSource = GetCustomList(1);
            DesignationComboBox.DisplayMember = "Description";
            //DesignationComboBox.ValueMember = "ListId";
            DesignationComboBox.ValueMember = "Description";
            DesignationComboBox.SelectedIndex = -1;
            //Job Category
            JobCategoryComboBox.DataSource = GetCustomList(2);
            JobCategoryComboBox.DisplayMember = "Description";
            JobCategoryComboBox.ValueMember = "Description";
            JobCategoryComboBox.SelectedIndex = -1;
            //Projects
        }
        private DataTable GetCustomList(int listType)
        {
            DataTable dt = new DataTable();
            string connString = ConfigurationManager.ConnectionStrings["abccs"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = conn;
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "usp_ListItems";
                    command.Parameters.AddWithValue("@ListType", listType);
                    conn.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    dt.Load(reader);
                }
            }
            return dt;
        }

COMPLETE CODE

CODE:


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace ABCWF
{
    public partial class EmployeeForm : Form
    {
        public EmployeeForm()
        {
            InitializeComponent();
        }

        private void SubmitButton_Click(object sender, EventArgs e)
        {
            InsertIntoDatabase();
        }

        private void InsertIntoDatabase()
        {
            try
            {
                string connString = ConfigurationManager.ConnectionStrings["abccs"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    using (SqlCommand command = new SqlCommand())
                    {
                        command.Connection = conn;
                        command.CommandType = CommandType.StoredProcedure;
                        command.CommandText = "usp_AddEmployee";
                        command.Parameters.AddWithValue("@FirstName", FirstNameTextBox.Text);
                        command.Parameters.AddWithValue("@LastName", LastNameTextBox.Text);
                        command.Parameters.AddWithValue("@Email", EmailTextBox.Text);
                        command.Parameters.AddWithValue("@IsVB", IsVBCheckBox.Checked);
                        command.Parameters.AddWithValue("@IsJava", IsJavaCheckBox.Checked);
                        command.Parameters.AddWithValue("@IsCSharp", IsCSharpCheckBox.Checked);
                        command.Parameters.AddWithValue("@Gender", GetGenderValue());
                        command.Parameters.AddWithValue("@Dob",
                        (DOBDateTimePicker.Text.Trim() == string.Empty) ? (DateTime?)null : DOBDateTimePicker.Value.Date);
                        command.Parameters.AddWithValue("@Tob", (TimeDateTimePicker.Text.Trim() == string.Empty) ? (TimeSpan?)null : TimeDateTimePicker.Value.TimeOfDay);
                        command.Parameters.AddWithValue("@Designation", DesignationComboBox.SelectedValue);
                        command.Parameters.AddWithValue("@JobCategory", JobCategoryComboBox.SelectedValue);
                        //Execute the insert query
                        conn.Open();
                        command.ExecuteNonQuery();
                        MessageBox.Show("Record inserted successfully.", "Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Insertion Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        enum Sex
        {
            OtherSex = 0,
            Male = 1,
            Female = 2
        }
        private int GetGenderValue()
        {
            if (MaleRadioButton.Checked)
            {
                return (int)Sex.Male;
            }
            if (FemaleRadioButton.Checked)
            {
                return (int)Sex.Female;
            }
            return (int)Sex.OtherSex;
        }

        private void DOBDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            DOBDateTimePicker.CustomFormat = "dd/MM/yyyy";
        }

        private void TimeDateTimePicker_ValueChanged_1(object sender, EventArgs e)
        {
            DateTimePicker dtp = (DateTimePicker)sender;
            dtp.CustomFormat = "HH:mm";
        }

        private void EmployeeForm_Load(object sender, EventArgs e)
        {
            //Designation
            DesignationComboBox.DataSource = GetCustomList(1);
            DesignationComboBox.DisplayMember = "Description";
            //DesignationComboBox.ValueMember = "ListId";
            DesignationComboBox.ValueMember = "Description";
            DesignationComboBox.SelectedIndex = -1;
            //Job Category
            JobCategoryComboBox.DataSource = GetCustomList(2);
            JobCategoryComboBox.DisplayMember = "Description";
            JobCategoryComboBox.ValueMember = "Description";
            JobCategoryComboBox.SelectedIndex = -1;
            //Projects
        }
        private DataTable GetCustomList(int listType)
        {
            DataTable dt = new DataTable();
            string connString = ConfigurationManager.ConnectionStrings["abccs"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = conn;
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "usp_ListItems";
                    command.Parameters.AddWithValue("@ListType", listType);
                    conn.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    dt.Load(reader);
                }
            }
            return dt;
        }
    }
}

INPUT DATA

OUTPUT

ComboBox Properties:

  • (Name)
  • Items
  • DataSource=
  • AllowDrop=False|True
  • AutoCompleteMode=Suggest
  • AutoCompleteSource=ListItems|CustomSource
  • DropDownStyle = Simple|Dropdown|DropdownList
  • ComboBox1.Sorted =true|false
  • SelectedItem
  • SelectedIndex

ComboBox Methods:

  • ComboBox1.Items.Add(Object SelectedItem)
  • ComboBox1.Items.RemoveAt(int number)
  • ComboBox1.Items.Remove(Object value)
  • ComboBox1.Items.Clear()

© अजीत कुमार, सर्वाधिकार सुरक्षित।

इस आलेख को उद्धृत करते हुए इस लेख के लिंक का भी विवरण दें। इस आलेख को कॉपीराइट सूचना के साथ यथावत साझा करने की अनुमति है। कृपया इसे ऐसे स्थान पर साझा न करें जहाँ इसे देखने के लिए शुल्क देना पडे।

No comments:

Post a Comment

Hot Topics