Cannot find reference for a control

rahul kumar 605 Reputation points
2023-07-15T12:51:36.1033333+00:00

Hi , Below is the code for my customdatagridview . Take a closer look at its constructor . I have changed it as i want to access any other datagridview which is present on the using form itself.

 public partial class betterdatagridview : DataGridView
    {
        public DataGridView dgv;
        private DataSet dataSet;
        public betterdatagridview( DataGridView dv)
        {
          ** // dgv = new DataGridView(); // no use **
            dgv = dv;
            InitializeComponent();            
            this.AllowUserToAddRows = false;
            this.AllowUserToResizeColumns = false;
            this.BorderStyle = BorderStyle.None;
            this.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.CellBorderStyle = DataGridViewCellBorderStyle.None;
            this.RowHeadersVisible = false;
           
        }
             
        protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
        {
            base.OnEditingControlShowing(e);
            TextBox txt = e.Control as TextBox;
            txt.TextChanged -= txt_TextChanged;
            txt.KeyDown -= new KeyEventHandler(txt_KeyDown);
            txt.Enter -= txt_Enter;
            txt.KeyPress -= new KeyPressEventHandler(txt_KeyPress);
            if (this.CurrentCell.ColumnIndex == 0)
            {   
                if (txt != null)
                {
                    txt.TextChanged += txt_TextChanged;                   
                    txt.KeyDown += new KeyEventHandler(txt_KeyDown);
                    txt.Enter += txt_Enter;
                }
            }
            if (this.CurrentCell.ColumnIndex == 1 || this.CurrentCell.ColumnIndex == 2) // Assuming the first column has an index of 0
            {   
                if (txt != null)
                {  
                    txt.KeyPress += new KeyPressEventHandler(txt_KeyPress);
                }
            }
        }

        private void txt_Enter(object sender, EventArgs e)
        {
            if (this.CurrentCell.ColumnIndex > 0)
                return;

            dgv.Visible = true; // runtime error as compiler reach here 
            dgv.Columns["id"].Visible = false;
            dgv.Columns["current_balance"].Visible = false;
            dgv.Columns["opening_balance"].Visible = false;
            dgv.CurrentCell = dgv.Rows[0].Cells[1];
        }   

    }
}

I am trying to use the above control on Form3 . Form 3 has two datagridviews . one is betterdatagridview and the other one is datagridview1 . Below is the designer code file for Form3 .

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
/// 



private Supercontrols.betterdatagridview betterdatagridview1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
private System.Windows.Forms.DataGridView dataGridView1;
private void InitializeComponent()
{

this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.betterdatagridview1 = new datagridviewusingchatgpt.Supercontrols.betterdatagridview(dataGridView1);
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();


this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.betterdatagridview1)).BeginInit();
this.SuspendLayout();


// 
// dataGridView1
// 
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(548, 12);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersWidth = 51;
this.dataGridView1.RowTemplate.Height = 24;
this.dataGridView1.Size = new System.Drawing.Size(240, 416);
this.dataGridView1.TabIndex = 3;
// 
// betterdatagridview1
// 
this.betterdatagridview1.AllowUserToAddRows = false;
this.betterdatagridview1.AllowUserToResizeColumns = false;
this.betterdatagridview1.BackgroundColor = System.Drawing.SystemColors.Control;
this.betterdatagridview1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.betterdatagridview1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.betterdatagridview1.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
this.betterdatagridview1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.betterdatagridview1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2});
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.betterdatagridview1.DefaultCellStyle = dataGridViewCellStyle1;
this.betterdatagridview1.Location = new System.Drawing.Point(2, 92);
this.betterdatagridview1.Name = "betterdatagridview1";
this.betterdatagridview1.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
this.betterdatagridview1.RowHeadersVisible = false;
this.betterdatagridview1.RowHeadersWidth = 51;
this.betterdatagridview1.RowTemplate.Height = 24;
this.betterdatagridview1.Size = new System.Drawing.Size(482, 135);
this.betterdatagridview1.TabIndex = 1;
// 
// Column1
// 
this.Column1.HeaderText = "Particulars";
this.Column1.MinimumWidth = 6;
this.Column1.Name = "Column1";
this.Column1.Width = 125;
// 
// Column2
// 
this.Column2.HeaderText = "amount";
this.Column2.MinimumWidth = 6;
this.Column2.Name = "Column2";
this.Column2.Width = 125;
// 
// form3
// 
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.betterdatagridview1);
this.Name = "form3";
this.Text = "form3";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.form3_FormClosing);
this.Load += new System.EventHandler(this.form3_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.betterdatagridview1)).EndInit();
this.ResumeLayout(false);

}

}



  public partial class form3 : Form
{

    public form3()
    {           
        InitializeComponent();            
     }


    private void form3_Load(object sender, EventArgs e)
    {
        dataGridView1.Visible = false;
        dataGridView1.ColumnHeadersVisible = false;
        dataGridView1.RowHeadersVisible = false;
        dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        dataGridView1.BorderStyle = BorderStyle.None;
        dataGridView1.ReadOnly = true;
        dataGridView1.MultiSelect = false;
        dataGridView1.AllowUserToResizeColumns = false;
        dataGridView1.AllowUserToResizeRows = false;
        dataGridView1.DataSource = connectionlogics.FillDataGridView($"SELECT * FROM ledgernames");

    }

}

I am getting an runtime error . Pls suggest how can i access and use the datagridview on my betterdatagridview .

User's image

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,798 questions
C#
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.
9,936 questions
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 17,506 Reputation points Microsoft Vendor
    2023-07-18T08:53:26.96+00:00

    Hi @rahul kumar , Welcome to Microsoft Q&A.

    If you want to operate other datagridviews, you only need to assign this datagridview to the dgv in your betterdatagridview on the code side of the main form. In order to avoid errors, you can also add the detection of whether the dgv is empty before your error code. The reason why you have this error is because your dgv does not have this id column.

    using System.Windows.Forms;
    
    namespace _7_18_cc
    {
        public partial class betterdatagridview : DataGridView
        {
            public DataGridView dgv;
            public betterdatagridview()
            {
                InitializeComponent();
            }
    
            protected override void OnPaint(PaintEventArgs pe)
            {
                base.OnPaint(pe);
            }
            protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
            {
                base.OnEditingControlShowing(e);
                dgv.Visible = true; // runtime error as compiler reach here 
                dgv.Columns["id"].Visible = false;
                dgv.CurrentCell = dgv.Rows[0].Cells[1];
            }
        }
    }
    
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;
    
    namespace _7_18_2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DemoDB;Integrated Security=True;Connect Timeout=30;";
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    try
                    {
                        connection.Open();
                        string sqlQuery = "SELECT * FROM TTable73";
                        using (SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, connection))
                        {
                            DataSet dataSet = new DataSet();
                            adapter.Fill(dataSet);
                            DataTable dataTable = dataSet.Tables[0];
                            betterdatagridview1.dgv = dataGridView1;
                            dataGridView1.DataSource = dataTable;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("An error occurred: " + ex.Message);
                    }
                }
            }
        }
    }
    

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 52,491 Reputation points
    2023-07-15T15:41:55.97+00:00

    You never added a column named “id”