How to change the data of datagridview when changes has made from another form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mylixes
    New Member
    • May 2010
    • 29

    How to change the data of datagridview when changes has made from another form

    I'm currently developing a windows application.

    I have two forms, Form1 and Form2. They are both open.

    In Form1, I have two dateTimePickers (start date and end date), two text boxes (no of records and no of days) and two buttons (submit and cancel). In Form2, I have a dataGridView that displays data from a text file.

    For example, I set the start date from form1 as May 5, 2010 and end date as May 6, 2010. After i click the submit button, form2 will read the text file and display the data that are >= start date and <= end date.
    Last edited by Niheel; May 6 '10, 03:02 PM. Reason: Removed hello and thanks, not relevant question details
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Originally posted by OriginalPoster
    Original Poster: How do I get my Form2 to react to something on my Form1?
    How do I make my Form1 control something on my Form2?
    Although you can have Form1 directly access items on Form2 it isn't the recommended way to go. It ties the two forms tightly to each other. If a change is made in Form2 such as removing one of the controls, then code in Form1 breaks.
    It is better to Form1 raise an event, and have Form2 contain its own code for how to react to this. This places responsibility for Form2 within Form2, and Form1 within Form1.
    It keeps Form1 blissfully ignorant of Form2 - and a logging component - and a progress component, and a dozen other little black boxes that can be subscribed to events in Form1, all without Form1 being made responsible for directly affecting controls other than itself.
    Events tutorial (including Form to Form which is the same as class to class)
    This tutorial for a cash register does exactly that: It makes a virtual numeric keyboard.

    Bad: Directly accessing controls of one class/form from another.
    Code:
    bool IsOn = Form2.button1.IsChecked;
    Good: Use a property to get such information
    Code:
    //Form1
    bool IsOn = Form2.IsOn;
    Code:
    //Form 2
    public bool IsOn
    {
       get { return CheckBox1.Checked; }
       set { CheckBox1.Checked = value; }
    }
    It's a subtle but important difference as your applications become more complex. Using properties means your target class/form (Form2) can be changed and updated a thousand different ways yet won't negatively impact the classes that are reading from it. If you change the name of a control for example: It won't break references in all your other classes. If your target form evolves where it needs to do 10 things when it is turned on, then the responsibility stays within Form2, and that burden is not put on Form1 and a dozen other forms that might be using Form2. The goal is to compartimentali ze the work so that Form2 is responsiblity SOLELY for Form2. From1 should only have to say "Turn on" or "Turn Off"

    Form2
    Code:
    public bool IsOn
    {
       get { return btnMeaningfulName.Checked; }
       set {
                btnMeaningfulName.Checked = value;
                panelDashboard.Visible = value;
                labelStatus = value == true ? "On" : "Off";
                btnRunNow.Enabled = value;
           }
    }
    Now when Form1 tells Form2 to turn on, Form2 will check a box, make an entire panel visible, change its Status label to say 'On' and enable a Run Now button.

    Comment

    • mylixes
      New Member
      • May 2010
      • 29

      #3
      Originally posted by tlhintoq
      Although you can have Form1 directly access items on Form2 it isn't the recommended way to go. It ties the two forms tightly to each other. If a change is made in Form2 such as removing one of the controls, then code in Form1 breaks.
      It is better to Form1 raise an event, and have Form2 contain its own code for how to react to this. This places responsibility for Form2 within Form2, and Form1 within Form1.
      It keeps Form1 blissfully ignorant of Form2 - and a logging component - and a progress component, and a dozen other little black boxes that can be subscribed to events in Form1, all without Form1 being made responsible for directly affecting controls other than itself.
      Events tutorial (including Form to Form which is the same as class to class)
      This tutorial for a cash register does exactly that: It makes a virtual numeric keyboard.

      Bad: Directly accessing controls of one class/form from another.
      Code:
      bool IsOn = Form2.button1.IsChecked;
      Good: Use a property to get such information
      Code:
      //Form1
      bool IsOn = Form2.IsOn;
      Code:
      //Form 2
      public bool IsOn
      {
         get { return CheckBox1.Checked; }
         set { CheckBox1.Checked = value; }
      }
      It's a subtle but important difference as your applications become more complex. Using properties means your target class/form (Form2) can be changed and updated a thousand different ways yet won't negatively impact the classes that are reading from it. If you change the name of a control for example: It won't break references in all your other classes. If your target form evolves where it needs to do 10 things when it is turned on, then the responsibility stays within Form2, and that burden is not put on Form1 and a dozen other forms that might be using Form2. The goal is to compartimentali ze the work so that Form2 is responsiblity SOLELY for Form2. From1 should only have to say "Turn on" or "Turn Off"

      Form2
      Code:
      public bool IsOn
      {
         get { return btnMeaningfulName.Checked; }
         set {
                  btnMeaningfulName.Checked = value;
                  panelDashboard.Visible = value;
                  labelStatus = value == true ? "On" : "Off";
                  btnRunNow.Enabled = value;
             }
      }
      Now when Form1 tells Form2 to turn on, Form2 will check a box, make an entire panel visible, change its Status label to say 'On' and enable a Run Now button.
      I appreciate your reply regarding this matter..
      Can you give me the code that can help me solve the problem?

      This is what I currently have:

      //when Submit button is click is Form1
      Code:
      private void btnSubmit_Click(object sender, EventArgs e)
              {
                  string startDate = "", endDate = "", prevDays = "", prevRecords = "";
      
                  if (rdbDate.Checked)
                  {
                      startDate = Convert.ToDateTime(dtpStartDate.Text).ToShortDateString();
                      endDate = Convert.ToDateTime(dtpEndDate.Text).ToShortDateString();
                      prevRecords = "";
                      prevDays = "";
                  }
                  else if (rdbPrevDays.Checked)
                  {
                      string[] str;
                      str = txtPrevDays.Text.Split(' ');
                      prevDays = str[0];
                      
                      prevRecords = "";
                      startDate = "";
                      endDate = "";
                  }
                  else
                  {
                      string[] str;
                      str = txtPrevRecords.Text.Split(' ');
                      prevRecords = str[0];
      
                      startDate = "";
                      endDate = "";
                      prevDays = "";
      
                  }
      
                  cashierLoginRecordsFrm = new FrmCashierLoginRecords(startDate, endDate, prevDays, prevRecords, 1);
      
                  int i = 0;
      
                  Form frm;
                  while (Application.OpenForms.Count > 1)
                  {
                      if (Application.OpenForms.Count == 2)
                      {
                          break;
                      }
                      else
                      {
                          if (i < Application.OpenForms.Count)
                          {
                              frm = Application.OpenForms[i];
                              if (frm.Name.Equals("FrmCashierLoginRecords"))
                              {
                                  Application.OpenForms[i].Close();
                                  break;
                              }
      
                              i++;
                          }
                          else
                              break;
      
                      }
                  }
      
                  cashierLoginRecordsFrm.Show();
      
              }

      //Form2
      Code:
      private void FrmCashierLoginRecords_Load(object sender, EventArgs e)
              {
                  Common.desiredLowerLocation.X = Common.panelLowerLocX;
                  Common.desiredLowerLocation.Y = Common.panelLowerLocY;
      
                  this.Location = new Point(Common.desiredLowerLocation.X, Common.desiredLowerLocation.Y);
      
                  int i = 0, x = 0;
                  string path = ".\\CashierRecord.txt";
      
      
                  string str = "";
                  string[] tempStr;
                  string[] result;
                  string[] splitTempStr;
                  string[] cashierCardNo = new string[10];
                  string[] date = new string[10];
                  string[] status = new string[10];
                  DateTime dateFromFile;
      
                  dataGridView1.Refresh();
                  dataGridView1.Rows.Add(9);
                  dataGridView1["Column2", 0].ValueType = System.Type.GetType("System.Date");
      
                  if (File.Exists(path))
                  {
                      tempStr = File.ReadAllLines(path);
      
                      if (Common.isCashierLoginTransactionHistory)
                      {
                          result = new string[10];
      
                          if (tempStr.Length < 10)
                          {
                              i = 0;
                              do
                              {
                                  if (i == tempStr.Length)
                                      break;
      
                                  if (!tempStr[i].StartsWith(";"))
                                  {
                                      result[i - 1] = tempStr[i];
      
                                  }
                                  i++;
      
                              }
                              while (i <= tempStr.Length);
      
                          }
                          else
                          {
                              Array.Copy(tempStr, tempStr.Length - 10, result, 0, 10);
                          }
      
                          Array.Reverse(result);
      
      
                          for (i = 0; i < 10; i++)
                          {
                              if (result[i] != null)
                              {
                                  if (!result[i].Equals(""))
                                  {
                                      splitTempStr = result[i].Split('\t');
      
                                      cashierCardNo[i] = splitTempStr[0];
                                      date[i] = splitTempStr[2];
                                      status[i] = splitTempStr[4];
      
                                      dataGridView1["Column1", i - x].Value = cashierCardNo[i];
                                      dataGridView1["Column2", i - x].Value = date[i];
                                      dataGridView1["Column3", i - x].Value = status[i];
                                  }
                                  else
                                  {
                                      x++;
                                  }
                              }
                              else
                              {
                                  x++;
                              }
                          }
                      }
                      else
                      {
                          string[] splitDate;
                          if (!dateStart.Equals("") && !dateEnd.Equals(""))
                          {
                              result = new string[10];
                              x = 0;
      
                              for (i = 0; i < tempStr.Length; i++)
                              {
                                  if (!tempStr[i].Equals(""))
                                  {
                                      if (!tempStr[i].StartsWith(";"))
                                      {
                                          if (x < result.Length)
                                          {
                                              splitTempStr = tempStr[i].Split('\t');
                                              cashierCardNo[x] = splitTempStr[0];
                                              date[x] = splitTempStr[2];
                                              status[x] = splitTempStr[4];
      
                                              splitDate = date[x].Split(' ');
      
                                              string[] str1 = splitDate[0].Split('/');
                                              string temp = "";
                                              temp = str1[0];
                                              str1[0] = str1[1];
                                              str1[1] = temp;
                                              string dt = str1[0] + "/" + str1[1] + "/" + str1[2];
                                              dateFromFile = Convert.ToDateTime(dt);
      
                                              if (DateTime.Parse(dateFromFile.ToShortDateString()) >= DateTime.Parse(dateStart) && DateTime.Parse(dateFromFile.ToShortDateString()) <= DateTime.Parse(dateEnd))
                                              {
                                                  result[x] = tempStr[i];
      
                                                  x++;
      
                                              }
                                              else
                                              {
                                                  continue;
                                              }
                                          }
                                          else
                                          {
                                              break;
                                          }
                                      }
                                  }
                              }
      
                              Array.Reverse(result);
      
                              for (i = 0; i < result.Length; i++)
                              {
                                  if (result[i] != null)
                                  {
                                      if (!result[i].Equals(""))
                                      {
                                          splitTempStr = result[i].Split('\t');
      
                                          cashierCardNo[i] = splitTempStr[0];
                                          date[i] = splitTempStr[2];
                                          status[i] = splitTempStr[4];
      
                                          dataGridView1["Column1", i].Value = cashierCardNo[i];
                                          dataGridView1["Column2", i].Value = date[i];
                                          dataGridView1["Column3", i].Value = status[i];
                                      }
                                      else
                                      {
                                          dataGridView1["Column1", i].Value = "";
                                          dataGridView1["Column2", i].Value = "";
                                          dataGridView1["Column3", i].Value = "";
                                      }
                                  }
                              }
                          }
                          else if (!previousRecords.Equals(""))
                          {
                              result = new string[tempStr.Length];
                              x = 0;
      
                              for (i = 0; i < tempStr.Length; i++)
                              {
                                  if (!tempStr[i].StartsWith(";"))
                                  {
                                      result[x] = tempStr[i];
                                      x++;
                                  }
                              }
      
                              Array.Reverse(result);
      
                              x = 0;
      
                              for (i = 0; i < int.Parse(previousRecords); i++)
                              {
                                  if (result[i] != null)
                                  {
                                      if (!result[i].Equals(""))
                                      {
                                          splitTempStr = result[i].Split('\t');
                                          cashierCardNo[i] = splitTempStr[0];
                                          date[i] = splitTempStr[2];
                                          status[i] = splitTempStr[4];
      
                                          dataGridView1["Column1", x].Value = cashierCardNo[i];
                                          dataGridView1["Column2", x].Value = date[i];
                                          dataGridView1["Column3", x].Value = status[i];
      
                                          x++;
                                      }
                                  }
                                  else
                                  {
      
                                  }
      
                              }
      
                          }
                          else if (!previousDays.Equals(""))
                          {
      
                          }
                          else
                          {
      
                          }
      
                          dataGridView1.Refresh();
                      }
                  }
              
              }
      additional question:
      is it possible if I will pass the data from Form1 to Form2 without closing and reopen the Form2 just to reflect the changes in the datagrid?

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        It helps the volunteers here tremendously when you post the actual code that is causing you problems. Not the entire application. Just the parts you have written that are causing the problem.

        1 - Copy the code from Visual Studio
        [imgnothumb]http://clint.stlaurent .net/bytes/code-copy.jpg[/imgnothumb]

        2 - In your question thread, click the [code] tags button. Its the one that looks like # symbol
        [imgnothumb]http://clint.stlaurent .net/bytes/tags-code.jpg[/imgnothumb]
        Code tags have magically appeared in your post with the cursor right between them.

        [code]|[/code]

        Just paste and you should see this
        [CODE] public void BrokenMethod()
        {
        // I don't understand why this doesn't work
        int Yogi = "Bear";
        }[/CODE]

        Which will look like this
        Code:
                public void BrokenMethod()
                {
                    // I don't understand why this doesn't work
                    int Yogi = "Bear";
                }
        More on tags. They're cool. Check'em out.

        Comment

        • tlhintoq
          Recognized Expert Specialist
          • Mar 2008
          • 3532

          #5
          I appreciate your reply regarding this matter..
          Can you give me the code that can help me solve the problem?
          So in other words you didn't even try to do it yourself. You just posted your entire application thus far and hope someone else will code it for you. No. That's not going to happen.

          If it's not important enough to you, to invest some of your own time to make an effort an *learn* ... then it has less importance to me. Let me be clear... It's not that I, or anyone here doesn't want to help you. We would love to help you. But I for one am not going to write it for you. Helping means you make your best effort, and show what you have done in an effort to accomplish and learn... and someone hear will help you clean up issues.

          Originally posted by Original Poster
          Can anybody send me code to [...]
          The Bytes volunteers are not here to write your code for you. This is not a free homework service.
          Bytes is very much a "Give me a fish I eat for a day. Teach me to fish I eat for a lifetime" kind of place. Just giving you the code doesn't help you learn near as effectively as good old-fashioned trial and error.

          Please research your problem before posting your question.
          A great place start your research is the MSDN library. This library is a bunch of articles and documentation provided by Microsoft about anything to do with .NET development. I recommend that you bookmark the resource for your future reference.

          After you research, do some experimenting. Then if your trials aren't doing what you expect, post the code and relevant messages/errors and we'll see what we can do to point you in the right direction for making it work.


          May I suggest picking up a basic C# introductory book? It's not that people here don't want to be helpful, but there is a certain amount of basic learning work that one should really take upon themselves before asking for help. There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" books at your look book seller or even public library... Asking a forum, any forum, to hand-hold you through it is just redundant. In many ways it disrespects the people who have invested dozens of hours in the on-line tutorials and those that spent thousands of hours in authoring books.

          Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
          is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

          C# Cookbooks
          Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

          Microsoft Visual Studio Tip, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
          Has many, many great, real-world tips that I use all the time.

          The tutorials below walk through making an application including inheritance, custom events and custom controls.
          Building an application Part 1
          Building an application part 2

          Comment

          • mylixes
            New Member
            • May 2010
            • 29

            #6
            Originally posted by tlhintoq
            It helps the volunteers here tremendously when you post the actual code that is causing you problems. Not the entire application. Just the parts you have written that are causing the problem.

            1 - Copy the code from Visual Studio
            [imgnothumb]http://clint.stlaurent .net/bytes/code-copy.jpg[/imgnothumb]

            2 - In your question thread, click the [code] tags button. Its the one that looks like # symbol
            [imgnothumb]http://clint.stlaurent .net/bytes/tags-code.jpg[/imgnothumb]
            Code tags have magically appeared in your post with the cursor right between them.

            [code]|[/code]

            Just paste and you should see this
            [CODE] public void BrokenMethod()
            {
            // I don't understand why this doesn't work
            int Yogi = "Bear";
            }[/CODE]

            Which will look like this
            Code:
                    public void BrokenMethod()
                    {
                        // I don't understand why this doesn't work
                        int Yogi = "Bear";
                    }
            More on tags. They're cool. Check'em out.
            oh sorry bout that..
            I just want to post the actual code i have for better understanding.

            Please just help me out with this.

            The program has no error.
            I just want some help how to make it more easier and reliable.

            Comment

            • tlhintoq
              Recognized Expert Specialist
              • Mar 2008
              • 3532

              #7
              The program has no error.
              Can you give me the code that can help me solve the problem?
              Which is it? You have an error or you don't?

              I just want some help how to make it more easier and reliable.
              Title: How to change the data of datagridview when changes has made from another form
              Again, which is it? You are trying to make it more reliable, or you want to know how to make form1 talk to form2?

              Please define exactly what the nature of your problem is, what code you have written that is causing the problem, and what help you would like.

              Comment

              • mylixes
                New Member
                • May 2010
                • 29

                #8
                Originally posted by tlhintoq
                Which is it? You have an error or you don't?



                Again, which is it? You are trying to make it more reliable, or you want to know how to make form1 talk to form2?

                Please define exactly what the nature of your problem is, what code you have written that is causing the problem, and what help you would like.
                I don't have any error in my code.
                I just want to know how to reflect the changes I made from Form1 to Form2 datagridView without closing and re-opening the Form2.

                Comment

                • tlhintoq
                  Recognized Expert Specialist
                  • Mar 2008
                  • 3532

                  #9
                  An example of communication from form1 to form2 has already been given.

                  The two tutorial links show this in even greater detail.
                  Build the two tutorial projects and you will learn.

                  Comment

                  • mylixes
                    New Member
                    • May 2010
                    • 29

                    #10
                    Originally posted by tlhintoq
                    An example of communication from form1 to form2 has already been given.

                    The two tutorial links show this in even greater detail.
                    Build the two tutorial projects and you will learn.
                    I read the link but in this code,

                    Code:
                     private void RaiseFeedback(string p)
                             {
                                 EventHandler<Saint.TextArgs> handler = Feedback;
                                 if (handler != null)
                                 {
                                     handler(null, new TextArgs(p));
                                 }
                             }
                    where should i get the "Saint" (EventHandler<S aint.TextArgs> handler = Feedback;)?

                    Comment

                    • mylixes
                      New Member
                      • May 2010
                      • 29

                      #11
                      Originally posted by mylixes
                      I read the link but in this code,

                      Code:
                       private void RaiseFeedback(string p)
                               {
                                   EventHandler<Saint.TextArgs> handler = Feedback;
                                   if (handler != null)
                                   {
                                       handler(null, new TextArgs(p));
                                   }
                               }
                      where should i get the "Saint" (EventHandler<S aint.TextArgs> handler = Feedback;)?
                      Oh sorry. I got it!

                      Comment

                      • tlhintoq
                        Recognized Expert Specialist
                        • Mar 2008
                        • 3532

                        #12
                        where should i get the "Saint" (EventHandler<S aint.TextArgs> handler = Feedback;)?
                        It is an example of how you could write your own event arguments. It represents whatever namespace you create as part of your project.

                        Notice if you make a new project named "widget" that the namespace for the project is 'widget'. Everyhing you make is wiithin that namespace. If you make a new class named "gadget" then a static property in that class named "thingie" you would reference it as 'widget.gadget. thingie'

                        This same is done in that example. It represents a custom event argument called 'TextArgs' with a project namespace of 'Saint'.

                        In your real project you would have a different namespace and you would make a different custom event Argument that matches your need.

                        If you were passing information about a retail product as an example you might make an argument of ProductArgs that contained properties of SKU, price and quantity.

                        Take a look at other event arts in the .NET framework and you will see how they contain different properties. KeyPressArgs contain a KeyCode property used to get the actual key pressed. ExceptionArg have a Message property.

                        For your project you will have to decide what data should be grouped together logically to make classes and args that get passed around via events.

                        Notice that in the tutorial we make the TextArgs class. That is the same one as Saint.TextArgs. It would just be inside your project's namespace instead.

                        Thank you for pointing out the confusing reference in my example. I have taken it out of the example in the hopes it doesn't confuse others. You can remove it from your project as well, if you are building the tutorial.

                        Comment

                        Working...