Form's control reference in CustomControl

OmkarHcl 206 Reputation points
2023-10-08T13:40:09.3833333+00:00
  public partial class sale_purchase_datagridview : DataGridView
    {
        private SqlConnection con;
        private SqlDataAdapter da;
        private DataTable dt, dt2;
        private DataSet dataSet;
        private DataView dataView;
        public sale_purchase_datagridview()
        {
            this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.BackgroundColor = Color.FromArgb(250, 243, 198);
            this.RowsDefaultCellStyle.BackColor = Color.FromArgb(250, 243, 198);
            this.DefaultCellStyle.SelectionBackColor = Color.FromArgb(168, 201, 170); // full row select color 
            this.RowHeadersVisible = false;
            this.CellBorderStyle = DataGridViewCellBorderStyle.None;
            this.ScrollBars = ScrollBars.None;
            this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.MultiSelect = false;
            this.AllowUserToResizeColumns = false;
            this.AllowUserToResizeRows = false;
            this.RowTemplate.Height = 30;

           // var column = this.Columns.GetLastColumn(DataGridViewElementStates.Visible,
                //                    DataGridViewElementStates.None);
          //  column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            InitializeComponent();
           
        }
        protected override void OnEnter(EventArgs e)
        {           
            this.CurrentCell = this.Rows[0].Cells[0];
            this.BeginEdit(true);  
            base.OnEnter(e);
        }

      
        protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
        {

            e.Control.KeyPress -= new KeyPressEventHandler(textbox_keypress);
            e.Control.TextChanged -= new EventHandler(TextBox_TextChanged);
            e.Control.KeyDown -= new KeyEventHandler(TextBox_KeyDown);
            e.Control.Enter -= new EventHandler(TextBox_Enter);
           if (this.CurrentCell.ColumnIndex == 0) // Assuming the first column has an index of 0
            {
                TextBox textBox = e.Control as TextBox;
                if (textBox != null)
                {
                    textBox.TextChanged += TextBox_TextChanged; // Attach TextChanged event handler
                    textBox.KeyDown += TextBox_KeyDown; // Attach KeyDown event handler
                    textBox.Enter += TextBox_Enter;
                }
            }
            base.OnEditingControlShowing(e);
        }

        private void TextBox_Enter(object sender, EventArgs e)
        {
            TextBox textBox = sender as TextBox;
           if (this.CurrentCell.ColumnIndex > 0)
                return;

            **dataGridView1**.Visible = true;
            **dataGridView1**.Datasource = something 
            **dataGridView1**.CurrentCell = **dataGridView1**.Rows[0].Cells[1];
        }


what i am trying is access the Form's control in the usercontrol itself . The intention is just to separte the usercontrol logic and form's logic . Please suggest what changes should i make to access the form's control in the usercontrol or should i change my strategy .

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. gekka 13,426 Reputation points MVP Volunteer Moderator
    2023-10-08T23:01:54.3433333+00:00

    Add a property to sale_purchase_datagridview that references an external DataGridView.
    This property must be preconfigured with the DataGridView to be referenced.

    It can set to the Property window at form designer.

    private void TextBox_Enter(object sender, EventArgs e)
    {
        TextBox textBox = sender as TextBox;
        if (this.CurrentCell.ColumnIndex > 0)
            return;
    
        if (this.LinkDataGridView != null)
        {
            this.LinkDataGridView.DataSource = "something";
            if (this.LinkDataGridView.Rows.Count > 0 && this.LinkDataGridView.Rows[0].Cells.Count > 0)
            {
                this.LinkDataGridView.CurrentCell = this.LinkDataGridView.Rows[0].Cells[1];
            }
        }
    }
    
    public DataGridView LinkDataGridView { get; set; }
    

1 additional answer

Sort by: Most helpful
  1. KOZ6.0 6,735 Reputation points
    2023-10-08T23:59:56.0533333+00:00

    You say "separate user control logic and formal logic", but you are not able to separate them. For example, OnEnter assumes that when this control get focus, there is at least one row and the first column is not ReadOnly.

    I recommend pasting the DataGridView into your UserControl, designing it, and using it. Then you will be able to write code that depends on the design.

    UseControlDemo

    Also, if you want to access the form's controls, pass them as properties. The following example is a delete button.

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    
    public partial class Sale_Purchase_DataGridView : UserControl
    {
        public Sale_Purchase_DataGridView() {
            InitializeComponent();
        }
    
        [Browsable(false)]
        public DataGridView DataGridView { get => dataGridView; }
    
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            // Your previous question is also answered here.
            // or You can do it by design.
            dataGridView.Columns[5].ReadOnly = true; // 4?
            var column = dataGridView.Columns.GetLastColumn(
                                DataGridViewElementStates.Visible,
                                DataGridViewElementStates.None);
            column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
    
        protected override void OnEnter(EventArgs e) {
            BeginInvoke((Action)(() => {
                dataGridView.Focus();
                dataGridView.CurrentCell = dataGridView[0, 0];
                dataGridView.BeginEdit(true);
            }));
            base.OnEnter(e);
        }
    
        private Button deleteButton;
    
        [Category("Buttons")]
        public Button DeleteButton {
            get {
                return deleteButton;
            }
            set {
                if (deleteButton != null) {
                    deleteButton.Click -= DeleteButton_Click;
                }
                deleteButton = value;
                if (deleteButton != null) {
                    deleteButton.Click += DeleteButton_Click;
                }
            }
        }
    
        private void DeleteButton_Click(object sender, EventArgs e) {
            if (CanDelete) {
                dataGridView.Rows.Remove(dataGridView.CurrentRow);
            }
        }
    
        protected virtual bool CanDelete {
            get {
                var current = dataGridView.CurrentRow;
                return current != null && !current.IsNewRow;
            }
        }
    }
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.