Solved

passing values to class

Posted on 2012-03-25
14
315 Views
Last Modified: 2012-04-09
Hi,

I am trying to pass a value from Form1 to Class1 but I not able to get it on Class1 in c# 2010 windows application.

Form1:
       public string _Ref
       {
          get { return txtRef.Text; }
       }

 private void btn_Click (object sender, EventArgs e)
       {
            // DBO is the name of class1
          DBO db = new DBO ();
          db._Ref2=_Ref;

          Form2 frm2 = new Form2();
          fmr2.Show();
      }

Class1:
   public class DBO: DataSet
   {
       private string Referernce=string.Empty;
       public string _Ref2
       {
          set { Referernce=value; }
       }


If I pass the same value to another form instead of a class then I can access it there.

Please help.

ayha
0
Comment
Question by:ayha1999
14 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 37764388
See here:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_27647727.html


ps - it is EXACTLY the same question as you are asking again.
0
 
LVL 5

Expert Comment

by:Vishal Kedar
ID: 37764389
try below code

Class1:
   public class DBO: DataSet
   {
       private string Referernce=string.Empty;
       public string _Ref2
       {
          get { return Referernce ; }
          set { Referernce=value; }
       }
0
 
LVL 7

Author Comment

by:ayha1999
ID: 37764628
Hi vishal_114,

still returns empty string.
0
 

Expert Comment

by:mehta_muktesh
ID: 37765337
Create a new class library add the class1 to that library and give reference of same in the windows form application. You should be able to access class members then.

Hope this helps!
0
 
LVL 9

Expert Comment

by:gery128
ID: 37765961
where are you accessing DBO class's _Ref property ? I could see this line is setting the value:
db._Ref2=_Ref;

but where exactly you intend to access this _Ref property ?
As you have created DBO class object in btn_Click object,
using this line DBO db = new DBO ();
you would be able to access db object in that method only and not the outside events functions globally.
0
 
LVL 40
ID: 37766085
First of all, you should send us copies of your exact code, not something that you retype as is evident with typing errors. Your code would not compile as it is presented (frm2 vs fmr2). When you retype code to simplify it, you often forgot the important part that causes the error.

An obvious one, but the type of evident thing that we all face in our debugging from time to time: is there something in txtRef when you test the mechanism?

How do you know that the value does not go through. With the code that you present us, _Ref2 is WriteOnly. If you test it in the debugger, you will see that the value does go in.

Finally, do not use an underscore as the first character of public variables and members. This is not CLS Compliant, meaning that some languages might have problems referencing your applications or dlls.
0
 
LVL 7

Author Comment

by:ayha1999
ID: 37766426
OK. I will post the complete code and what I am trying achieve.

fSearch: (a search form)
I want to pass the value of txtRegNo.Text to Class1.

       public string _RegNo
       {
          get { return txtRegNo.Text; }
       }

       private void btnSearch_Click (object sender, EventArgs e)
       {
          Form2 frm2 = new Form2 ();
          DBO db = new DBO ();
          db._RegNo=_RegNo;
          frm2.Show ();
       }

Class1: (This class is used for creating an object datasource for populating a reportViewer control and is called in Form2 where reportViewer is placed.)

namespace DataClass
{
    public partial class DBO : DataSet
    {
        private DataTable dt;
        public string _RegNo
        {
            set { RegNo = value; }
        }
        private string RegNo= string.Empty;

        public DBO()
        {
            OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyProject\MyDb.accdb;Jet OLEDB:Database Password=pwd;");
            OleDbDataAdapter da = new OleDbDataAdapter("select RegNo, Make, Model from cars where regno = '" + RegNo + "'", cn);
            DataSet ds = new DataSet();
            cn.Open();

            da.Fill(ds);

            dt = new DataTable("Auto");
            dt.Columns.Add("RegNo", typeof(string));
            dt.Columns.Add("Make", typeof(string));
            dt.Columns.Add("Model", typeof(string));

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                dt.Rows.Add(dr["regNo"].ToString(), dr["Make"].ToString(), dr["Model"].ToString());
            }
            Tables.Add(dt);
        }
    }
}

Form2:
       private void Form2_Load (object sender, EventArgs e)
       {
          DBO db2 = new DBO ();

          DBOBindingSource.DataMember="Auto";
          DBOBindingSource.DataSource=db2;
          this.reportViewer1.RefreshReport ();
       }

The problem is when the reportViewer is loaded, no data is in it even if the correct regno is provided. If I hardcode  private string RegNo= "5487"; then it retrieves the correct record, means the regno is not reaching in class1.

Thanks
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 40
ID: 37766784
OK. Better when we have the whole picture. I think I have nailed it.

You give a value to the db object that you create in Form1.

In Form2 you create a new DBO object. This is not the same object (variable). So the value that you passed in Form1 is not visible.

What I would to is create a constructor in Form2 that accepts the value in the textbox. That way, Form2 will have the necessary information in instantiate its own DBO object. Something like the following:

      public class Form2 : Form
            {
            public Form2 ( string regNo )
                  {
                  InitializeComponent ( );

                  DBO db2 = new DBO ( );
                  db2._RegNo = regNo;

                  DBOBindingSource.DataMember = "Auto";
                  DBOBindingSource.DataSource = db2;
                  this.reportViewer1.RefreshReport ( );

                  }
            }

When you launch Form2 from Form1, pass the value:

Form2 frm2 = new Form2 (txtRef.Text);
0
 
LVL 7

Author Comment

by:ayha1999
ID: 37766911
I modied the code as follows.

search form:
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2(txtRegNo.Text);
            frm2.Show();
        }

form2:
        public Form2(string regNo)
        {
            InitializeComponent();
            DBO db2 = new DBO();
            db2._RegNo = regNo;
            DBOBindingSource.DataMember = "Auto";
            DBOBindingSource.DataSource = db2;
            this.reportViewer1.RefreshReport();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

and no changes in the class1. still not getting any record. may be something wrong in my implementation? Nothing in the form load event of form2 now.

thanks
0
 
LVL 1

Accepted Solution

by:
Memcculloch earned 250 total points
ID: 37767719
  DBO db2 = new DBO(); //Query is performed when object created
            db2._RegNo = regNo; //Search is already complete, to late to set parameter
            DBOBindingSource.DataMember = "Auto";
            DBOBindingSource.DataSource = db2;
            this.reportViewer1.RefreshReport();

Open in new window


Your class DBO is performing it's query search when it is constructed using the initial value of  "private string RegNo= string.Empty;".  You are then setting RegNo equal to your search string, but the search has already been completed.

If you want to perform the search during the creation of the DBO object, then you should pass the RegNo in the constructer, like so:

namespace DataClass
{
    public partial class DBO : DataSet
    {
        private DataTable dt;

        /* Commented out as unneeded
        public string _RegNo
        {
            set { RegNo = value; }
        }
        private string RegNo= string.Empty; */

        public DBO(string regNo)
        {
            OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyProject\MyDb.accdb;Jet OLEDB:Database Password=pwd;");
            OleDbDataAdapter da = new OleDbDataAdapter("select RegNo, Make, Model from cars where regno = '" + RegNo + "'", cn);
            DataSet ds = new DataSet();
            cn.Open();

            da.Fill(ds);

            dt = new DataTable("Auto");
            dt.Columns.Add("RegNo", typeof(string));
            dt.Columns.Add("Make", typeof(string));
            dt.Columns.Add("Model", typeof(string));

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                dt.Rows.Add(dr["regNo"].ToString(), dr["Make"].ToString(), dr["Model"].ToString());
            }
            Tables.Add(dt);
        }
    }
}

Open in new window


Then pass the string into the constructor when loading form 2 like:
DBO db2 = new DBO(regNo);
0
 
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 250 total points
ID: 37768063
As you can see be combining my suggestion with the complement of Memcculloch, you should take the good habit of exploring the possibility of using constructors when you want to pass parameters from one class to another.

A property is useful when you need to keep a value for future reference. In your case, the value is used only once, so a property is not the right way to go. Passing a value to the constructor is usually a better technique in that case.

Put otherwise, most of the time, when you have a WriteOnly property (a set but no get), you have a great candidate for a parameter passed to the constructor instead of a property.
0
 
LVL 7

Author Comment

by:ayha1999
ID: 37769764
I have already tried the Public DBO (string regno) sub but failed to create report. Please see the images 1-6. 1-4 are same for both but the difference 5 and 6.

After creating the DataClass, I compile it, then select that class using object datasource. with public DBO(), the fields are available but with public(string regno), the fields are not available and I not able create report.

My goal is to filter the report, it doesn't matter what way I use. I want to select a record with the provided regno.

If any other way to achieve this goal,please provide it.

image 1image 2image 3image 4image 5imagr 6
Thanks
0
 
LVL 7

Author Comment

by:ayha1999
ID: 37823168
I found the solution. It is working by passing regno.

public class Cars
{
   private string m_regno;
   private string m_make;
   private string m_model;

   public Cars (string regno, string make, string model)
   {
       m_regno = regno;
       m_make = make;
       m_model = model;
   }

   public string regno
   {
       get
       {
          return m_regno;
       }
   }

   public string make
   {
       get
       {
          return m_make;
       }
   }

   public string model
   {
       get
       {
          return m_model;
       }
   }
}

public class car_list
{
   private List<Cars> m_cars;

   public car_list (string regno)
   {
       OleDbConnection cn = new OleDbConnection (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\mydb.accdb;Jet OLEDB:Database Password=pwd;");
       OleDbDataAdapter da = new OleDbDataAdapter ("select RegNo, Make, Model from cars where regno = '" + regno + "'", cn);
       DataSet ds = new DataSet ();
       cn.Open ();

       da.Fill (ds);

       foreach (DataRow dr in ds.Tables[0].Rows)
       {
          m_cars = new List<Cars> ();
          m_cars.Add (new Cars (dr["regNo"].ToString (), dr["Make"].ToString (), dr["Model"].ToString ()));
       }
   }

   public List<Cars> GetCars ( )
   {
       return m_cars;
   }
}

ayha
0
 
LVL 7

Author Closing Comment

by:ayha1999
ID: 37823173
Thanks for your suggestions and support.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now