Thursday, 21 August 2014

Windows Forms da User Controldan foydalanish

Using User Controls in Windows Forms Applications

Windows Formsdagi UserControl base-sinfidan foydalanib User Conrol hosil qilishimiz va undan foydalanishimiz mumkin.
User Controldan qayta foydalanishga va buglarni tezda aniqlashga qulayligi uchun ishlatiladi. Agar kodda biron o’zgartirish kiritilsa User Control chaqirilgan boshqa formalarga ham ta’sir qiladi. Bu texnologiyadan foydalanib ketadigan vaqtni tejash mumkin.
Quyida Ro’yxatga Insert,Udate,Delete qilishda User Control dan foydalanishni ko’rib chiqamiz.
1.  Visual Studio da File-New Project-Windows Forms Application ni tanlaymiz va Project nomi sifatida “UserControlTest1” ni kiritamiz.



2.        Form1.cs sinfi nomini “MainForm”ga, uning Text svoystvasini esa “User Control Test” ga o’zgartiramiz.
3.  “MainForm”ning ekran o’rtasidan chiqishini this.StartPosition=FormStartPosition.CenterScreen; orqali amalga oshiramiz.
4.        Proyektga “Models” nomli papka qo’shamiz, va u papkada talabalar haqidagi ma’lumotlarni aniqlashda kerak bo’ladigan Student sinfini hosil qilamiz:
namespace UserControlTest1.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Fio { get; set; }
        public string Fakultet { get; set; }
        public string Kurs { get; set; }
        public string Adress { get; set; }
    }
}
5.       MainFormda “yangi”, “o’zgartirish”, ”o’chirish” tugmalarini va talabalar ro’yxati uchun ListBoxni yaratamiz:

va Forma sinfida private List<Models.Student> students; ro’yxatini e’lon qilamiz va unga boshlang’ich qiymatlarni to’ldirish, ListBoxga yuklash uchun Init() metodini yaratamiz:
MainForm.cs:
namespace UserControlTest1
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            this.StartPosition=FormStartPosition.CenterScreen;
            this.MinimizeBox = false;
            this.MaximizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            Init();
        }
       
        //Boshlang'ich ma'lumotlarni Init qilish
        private void Init()
        {
            students=new List<Student>();
            students.Add(new Student() { Id = 1, Fio = "Student1", Adress = "adress1", Fakultet = "fakultet", Kurs = "1-b"});
            students.Add(new Student() { Id = 2, Fio = "Student2", Adress = "adress2", Fakultet = "fakultet", Kurs = "1-b" });
            students.Add(new Student() { Id = 3, Fio = "Student3", Adress = "adress3", Fakultet = "fakultet", Kurs = "1-b" });
            students.Add(new Student() { Id = 4, Fio = "Student4", Adress = "adress4", Fakultet = "fakultet", Kurs = "1-b" });
            students.Add(new Student() { Id = 5, Fio = "Student5", Adress = "adress5", Fakultet = "fakultet", Kurs = "2-b" });
            lBStudents.DataSource = students;
            lBStudents.DisplayMember = "Fio";
            lBStudents.ValueMember = "Id";
        }
        private List<Models.Student> students;
        //User Controlda OK tugmasi bosilganda chaqiriladigan metod
        private void Updated(object sender, EventArgs e)
        {
            var student = (sender as Student);
            if (student != null)
            {
                if (student.Id == -1) //Yangi student!
                {
                    int maxId = students.Max(max => max.Id);
                    student.Id = maxId + 1;
                    students.Add(student);
                    RefreshStudentsList();
                }

                else
                {
                    //Mavjud student haqidagi ma'lumotlarni o'zgartirish
                    var st=students.Find(f => f.Id == student.Id);
                    if (st != null)
                    {
                        st.Id = student.Id;
                        st.Fio = student.Fio;
                        st.Fakultet = student.Fakultet;
                        st.Kurs = student.Kurs;
                        st.Adress = student.Adress;
                        RefreshStudentsList();
                    }
                }
            }
        }
        //ListBox elementi itemlarini Refresh qilish
        private void RefreshStudentsList()
        {
            lBStudents.DataSource = null;
            lBStudents.DataSource = students;
            lBStudents.DisplayMember = "Fio";
            lBStudents.ValueMember = "Id";
        }
        //yangi tugmasi bosilganda:
        private void btnNew_Click(object sender, EventArgs e)
        {
            UC_AppUpdStudentInfo f=new UC_AppUpdStudentInfo();
            f.Updated += Updated;
            f.GetDialogForm().ShowDialog();
        }
        //O'zgartirish tugmasi bosilganda:
        private void btnUpd_Click(object sender, EventArgs e)
        {
            //Ro'yxat bo'sh emasligini tekshiramiz:
            if (lBStudents.SelectedItem != null)
            {
                var student = lBStudents.SelectedItem as Student;
                UC_AppUpdStudentInfo f = new UC_AppUpdStudentInfo(){StudentData = student};
                f.Updated += Updated;
                f.GetDialogForm().ShowDialog();
            }
        }
        //O'chirish tugmasi bosilganda:
        private void btnDel_Click(object sender, EventArgs e)
        {
            //Ro'yxat bo'sh emasligini tekshiramiz:
            if (lBStudents.SelectedItem != null)
            {
                var st = lBStudents.SelectedItem as Student;
                string studentInfo = string.Format("Fio:{0}\r Fakultet:{1}\r Kurs:{2}", st.Fio, st.Fakultet, st.Kurs);
                if (
                    MessageBox.Show("Quyidagi studentni ro'yxatdan o'chirishni tasdiqlaysizmi?\r" + studentInfo,
                        "O'chirishni tasdiqlash", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) ==
                    DialogResult.OK
                    ) students.Remove(st);
                RefreshStudentsList();
            }
        }
    }
}
6.       Proyektga “BaseDialogForm” nomli yangi forma qo’shamiz, bu formada ro’yxatdan tanlangan student haqidagi ma’lumotlarni o’zgartirish yoki yangi student haqidagi ma’lumotni kiritishda chaqiriladigan User Controlni chaqiramiz. Bu formada “OK” , “Bekor qilish” tugmalarini va User Control joylashishi uchun Panel hosil qilamiz hamda FormBorderStyle propertysini FixedSinglega, AcceptButton propertisini BtnOKga(Formada “Enter” tugmasi bosilganda OK eventi chaqirilishi uchun), CancleButton propertisini esa btnClosega o’zgartiramiz:

BaseDialogForm.cs:

namespace UserControlTest1
{
    public partial class BaseDialogForm : Form
    {
        //Usgbu control UserControlni joylashtirish uchun ishlatiladi
        public Control MainPanel
        {
            set
            {
                this.panel1.Controls.Add(value);
            }
        }

        public EventHandler OK_Click;//Bu Event qaysi User Control chaqirilsa o'shaning ichida aniqlanadi
        public BaseDialogForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (OK_Click != null)
                OK_Click(sender, e);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public void CloseForm()
        {
            this.Close();
        }
    }
}

7.       Proyektga User Control qo’shamiz va uni UC_AddUpdStudentInfo deb nomlab, unda Student haqidagi ma’lumotlarga mos forma elementlarini joylashtiramiz:

UC_AppUpdStudentInfo.cs:
namespace UserControlTest1
{
    public partial class UC_AppUpdStudentInfo : UserControl
    {
        public UC_AppUpdStudentInfo()
        {
            InitializeComponent();
        }

        private BaseDialogForm _dialogForm;
        public event EventHandler Updated;//Ushbu event User Control chaqirilayotgan formada aniqlanadi
        //Parent formani dinamik bog'lash
        public BaseDialogForm GetDialogForm()
        {
            _dialogForm=new BaseDialogForm();
            _dialogForm.MainPanel = this;
            _dialogForm.OK_Click += OK_Click;
            return _dialogForm;
        }

        private string _title;
        public string Title
        {
            get { return _title; }
            set { this.Text = value; }
        }

        private Student _studentdata;
        public Student StudentData
        {
            get { return GetStudentData(); }
            set
            {
                edtFio.Text = value.Fio;
                edtFakultet.Text = value.Fakultet;
                edtKurs.Text = value.Kurs;
                edtAdress.Text = value.Adress;
                _studentdata = value;
            }
        }

        private Student GetStudentData()
        {
            return new Student()
            {
                Id = GetCurrentStudentId(),
                Fio = edtFio.Text,
                Fakultet = edtFakultet.Text,
                Kurs = edtKurs.Text,
                Adress = edtAdress.Text
            };
        }

        private int GetCurrentStudentId()
        {
            int id = -1;
            if (_studentdata != null) id = _studentdata.Id;
            return id;
        }

        private void OK_Click(object sender, EventArgs e)
        {
            if (Updated != null)
            {
                Updated(GetStudentData(),new EventArgs());
                _dialogForm.DialogResult=DialogResult.OK;
                _dialogForm.Close();
            }
        }
    }
}

Xulosa qiladigan bo’lsak, User Controllardan yirik proyektlarda foydalanish qulay. Ayniqsa User Controlda aniqlangan Eventni u chaqiriladigan formalarda turlicha aniqlash mumkinligi va aksincha User Controlga mos Formada e’lon qilingan Eventni User Control ichida aniqlab turli parametrlarni boshqarish qulayligi tahsinga loyiq!  



Projectni to'laligicha quyidagi LINKdan yuklab olishingiz mumkin: https://www.dropbox.com/s/34n7o6wb7ddl575/UserControlTest1.rar

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Tasks and Threads

  Differences Between Task And Thread: 1. The Thread class is used for creating and manipulating a thread in Windows.  2. A Task represents ...