Thursday, April 23, 2020

How to use combobox using c#



This code shows how we can use combobox in our winforms application using c#.


    public partial class frmComboBox_Demo : Form
    {
        public frmComboBox_Demo()
        {
            InitializeComponent();

            comboBox1.Items.Add("Item 4");
            comboBox1.Items.Add("Item 5");
            comboBox1.Items.Add("Item 6");

            comboBox1.SelectedIndex = 2;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Selected text of combobox is: " + comboBox1.SelectedText);
            MessageBox.Show("Text of combobox is: " + comboBox1.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            comboBox1.Focus();
            MessageBox.Show("Selected text of combobox is: " + comboBox1.SelectedText);
            MessageBox.Show("Text of combobox is: " + comboBox1.Text);
        }

    }



How to fill datagridview from List using c#



This code shows how we can display a datatable in the datagridview in our windows form application using c#.


public partial class frmFillDataGridView_With_List : Form
    {
        public frmFillDataGridView_With_List()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                List<User> lstUser = new List<User>();
                lstUser.Add(new User
                {
                    IDCardNo = "23344-1234567-7",
                    Name = "John Doe",
                    Phone = "(+1)-123-333333",
                    Address = "Street 1, Isb, Pak"
                });
                lstUser.Add(new User
                {
                    IDCardNo = "23344-1234567-7",
                    Name = "John Albert",
                    Phone = "(+92)-199-3110003",
                    Address = "Street 2, Wah Cantt, Pak"
                });
                lstUser.Add(new User
                {
                    IDCardNo = "23344-1234567-9",
                    Name = "John Elsi",
                    Phone = "(+97)-777-5422433",
                    Address = "Street 3, Rwp, Pak"
                });
                dataGridView1.DataSource = lstUser;
            }
            catch (Exception ex)
            {

            }
        }
    }

    public class User
    {
        public string IDCardNo { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }

    }


How to display data in datagridview from datatable using C#


This code shows how we can display a datatable in the datagridview in our windows form application using c#.



public partial class frmFillDataGridView_With_Datatable : Form
    {
        public frmFillDataGridView_With_Datatable()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ID Card", typeof(string));
                dt.Columns.Add("Name", typeof(string));
                dt.Columns.Add("Father Name", typeof(string));
                dt.Columns.Add("Phone", typeof(string));
                dt.Columns.Add("Address", typeof(string));
                dt.Rows.Add("23344-1234567-7", "John Doe", "Elma, Rocks", "(+1)-123-333333", "Street 1, Isb, Pak");
                dt.Rows.Add("23344-1234567-8", "John Albert", "Rocky, Hun", "(+92)-199-3110003", "Street 2, Wah Cantt, Pak");
                dt.Rows.Add("23344-1234567-9", "John Elsi", "Jimmy, Adams", "(+97)-777-5422433", "Street 3, Rwp, Pak");
                dataGridView1.DataSource = dt;
            }
            catch (Exception ex)
            {

            }
        }
    }

How to restrict user to drag a form outside the screen bounds



This code shows how we can restrict our winform within screen bounds in our windows form application using c#.



 public partial class frmLogin_restrictWithin_ScreenBounds : Form
    {
        private bool mouseDown;
        private Point lastLocation;
        public frmLogin_restrictWithin_ScreenBounds()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            IntPtr ptr = NativeMethods.CreateRoundRectRgn(15, 15, this.Width, this.Height, 40, 40); // _BoarderRaduis can be adjusted to your needs, try 15 to start.
            this.Region = System.Drawing.Region.FromHrgn(ptr);
            NativeMethods.DeleteObject(ptr);
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDown = true;
                lastLocation = e.Location;
            }
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseDown)
            {
                this.Location = new Point(
                    (this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);

                this.Update();
            }
        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            if (mouseDown)
            {
                var currHandleScreen = Screen.FromControl(this);
                if (this.Bounds.Top < currHandleScreen.Bounds.Top)
                    this.Location = new Point(this.Location.X, currHandleScreen.WorkingArea.Top);
                else if (this.Bounds.Right > currHandleScreen.Bounds.Right)
                    this.Location = new Point(currHandleScreen.WorkingArea.Right - this.Width, currHandleScreen.WorkingArea.Top);
                else if (this.Bounds.Left < currHandleScreen.Bounds.Left)
                    this.Location = new Point(currHandleScreen.WorkingArea.Left, currHandleScreen.WorkingArea.Top);
                else if (this.Bounds.Bottom > currHandleScreen.Bounds.Bottom)
                    this.Location = new Point(this.Location.X, currHandleScreen.WorkingArea.Top);
            }
            mouseDown = false;
        }

    }

    public class NativeMethods
    {
        [System.Runtime.InteropServices.DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        public static extern System.IntPtr CreateRoundRectRgn
         (
          int nLeftRect, // x-coordinate of upper-left corner
          int nTopRect, // y-coordinate of upper-left corner
          int nRightRect, // x-coordinate of lower-right corner
          int nBottomRect, // y-coordinate of lower-right corner
          int nWidthEllipse, // height of ellipse
          int nHeightEllipse // width of ellipse
         );

        [System.Runtime.InteropServices.DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        public static extern bool DeleteObject(System.IntPtr hObject);
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

    }



How to open different types of files using OpenFileDialog in c#



This code shows how we can select different types of files using Openfilediaog in our windows form application using c#.




public partial class frm_OpenFileDialogue : Form
    {
        public frm_OpenFileDialogue()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "Text Files|*.txt";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox7.Text = dlg.FileName;
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "Word Documents|*.doc;*.docx";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dlg.FileName;
            }
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "Excel Worksheets|*.xlx;*.xlsx";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox2.Text = dlg.FileName;
            }
        }

        private void btnPowerPoint_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "Powerpoint Presentations|*.ppt;*.pptx";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox3.Text = dlg.FileName;
            }
        }

        private void btnOfficeFiles_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "Office Files|*.doc;*.docx;*.xls;*.xlsx;*.ppt; *.pptx";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox4.Text = dlg.FileName;
            }
        }

        private void btnAllFiles_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "All Files|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox5.Text = dlg.FileName;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            // Filter by Word Documents OR Excel Worksheets OR PowerPoint Presentations 
            //           OR Office Files 
            //           OR All Files
            dlg.Filter = "Word Documents|*.doc;*.docx|Excel Worksheets|*.xls;*.xlsx|PowerPoint Presentations|*.ppt;*.pptx" +
                         "|Office Files|*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx" +
                         "|All Files|*.*";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox6.Text = dlg.FileName;
            }
        }

    }

How to make rounded corners Winform using C#



This code shows how we can use make rounded corners form in our windows form application using c#.



public partial class frmLogin_roundedCorners : Form
    {
        public frmLogin_roundedCorners()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            IntPtr ptr = NativeMethods.CreateRoundRectRgn(15, 15, this.Width, this.Height, 40, 40); // _BoarderRaduis can be adjusted to your needs, try 15 to start.
            this.Region = System.Drawing.Region.FromHrgn(ptr);
            NativeMethods.DeleteObject(ptr);
        }

        #region Make draggable

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                NativeMethods.ReleaseCapture();
                NativeMethods.SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        #endregion
    }

    public class NativeMethods
    {
        [System.Runtime.InteropServices.DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        public static extern System.IntPtr CreateRoundRectRgn
         (
          int nLeftRect, // x-coordinate of upper-left corner
          int nTopRect, // y-coordinate of upper-left corner
          int nRightRect, // x-coordinate of lower-right corner
          int nBottomRect, // y-coordinate of lower-right corner
          int nWidthEllipse, // height of ellipse
          int nHeightEllipse // width of ellipse
         );

        [System.Runtime.InteropServices.DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        public static extern bool DeleteObject(System.IntPtr hObject);
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
    }



How to use ErrorProvider using C#



This code shows how we can use error provider on our windows form application using c#.


    public partial class frmLogin_errorProvider : Form
    {
        public frmLogin_errorProvider()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                errorProvider1.SetError(txtPassword, "Password is required.");
                txtPassword.Focus();
            }
            if (string.IsNullOrEmpty(txtUsername.Text))
            {

                errorProvider1.SetError(txtUsername, "Username is required.");
                txtUsername.Focus();
            }
            // Our code processing starts here.
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

How to use combobox using c#

This code shows how we can use combobox in our winforms application using c#.     public partial class frmComboBox_Demo : Form     {...