Making a reference to an object

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cainnech
    New Member
    • Nov 2007
    • 132

    Making a reference to an object

    Hello guys,

    In a project I'm building I have 4 datagrids which I'm using and where I'm updating information manually, so not from a database or a list.

    Now to make it a bit easier I would like to use one generic sort of variable to prevent having to write the same code 4 times.

    So if I have 4 datagridviews DataGrid1 through DataGrid4 I would like to be able to assign one of those Datagridview to a general object that has all of the properties and methods in it.

    I was thinking of using something like this:
    Code:
    object DataGrid = DataGrid1
    
    DataGrid.Rows.Add("INFO");
    But that doesn't work.
    Any idea on how to do this?

    Cheers,
    Cainnech
  • MichaelvdB
    New Member
    • Mar 2014
    • 2

    #2
    I think what you want is data binding using objects. (Note this code is using DataGridView for the DataGrids.)

    DGData.cs (Data Model Object):
    Code:
    using System;
    using System.ComponentModel;
    
    namespace DataGridTest
    {
       class DGData
       {
          private string _name;
          public DGData(string name) {
             _name = name;
          }
    
          public static implicit operator DGData(string name) {
             return new DGData(name);
          }
    
          [DisplayName("My Column Name")]
          public string Name {
             get { return _name; }
             set { _name = value; }
          }
       }
    }
    A form with two grids:
    Code:
    using System;
    using System.ComponentModel;
    using System.Data;
    using System.Windows.Forms;
    
    namespace DataGridTest
    {
       public partial class Form1 : Form
       {
          public Form1() {
             InitializeComponent();
          }
    
          private void Form1_Load(object sender, EventArgs e) {
             InitList(_dataGridView1);
             InitList(_dataGridView2);
          }
    
          static DGData[] _staticList = new DGData[] { "One", "Two", "Three" };
    
          static void InitList(DataGridView dgv) {
             // The data source can be modified in this case
             dgv.DataSource = new List<DGData>(_staticList);
          }
    
          static void InitList2(DataGridView dgv) {
             // The data source is fixed length
             dgv.DataSource = _staticList;
          }
       }
    }
    Last edited by MichaelvdB; Mar 19 '14, 04:53 AM. Reason: Technical update.

    Comment

    Working...