Для нестатического поля, метода или свойства требуется ссылка на объект - C# (189830)

Узнай цену своей работы

Формулировка задачи:

Замучился уже. Кто может помочь? Есть 2 datagrid заполняемых динамически (по регистрации карточек в микрофонах) Нужно то всего лишь сравнить если человек зарегистрировал карточку в микрофоне но не нажал кнопку добавить его в datagrid на другой форме. Пришел на ум такой метод, но пишет, что требуется ссылка на объект. ПОМОГИТЕ НОВИЧКУ ПОЖАЛУЙСТА))
Форма из которой должно считать
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Globalization;
  10. namespace DcnSwSmd
  11. {
  12. /// <summary>
  13. /// Form to display the Attendance Registration details.
  14. /// </summary>
  15. public partial class AttendanceRegistrationForm : Form
  16. {
  17. #region Methods
  18. /// <summary>
  19. /// Contructor.
  20. /// </summary>
  21. public AttendanceRegistrationForm()
  22. {
  23. InitializeComponent();
  24. miFullScreen.Checked = true;
  25. miFullScreen.Text = "Full Screen";
  26. miFullScreen.Click += new EventHandler(OnFullScreenClick);
  27. cmIndvResults.MenuItems.Add(miFullScreen);
  28. this.ContextMenu = cmIndvResults;
  29. this.headerControl.lblTimeLimit.Visible = false;
  30. }
  31.  
  32. /// <summary>
  33. /// Function to load the required data to display.
  34. /// </summary>
  35. /// <param name="participantinfo"></param>
  36. public delegate void UpdateAttendanceRegistrationData(SMDParticipantData participantInfo);
  37. public void LoadAttendanceRegistratioData(SMDParticipantData participantinfo)
  38. {
  39. if (this.InvokeRequired)
  40. {
  41. UpdateAttendanceRegistrationData obj = new UpdateAttendanceRegistrationData(LoadAttendanceRegistratioData);
  42. this.Invoke(obj, participantinfo);
  43. }
  44. else
  45. {
  46. if (participantinfo != null)
  47. {
  48. DataTable participantInformation = new DataTable();
  49. DateTime.Now.ToShortDateString().ToString(CultureInfo.InvariantCulture);
  50. this.headerControl.lblTime.Text = DateTime.Now.ToShortTimeString().ToString(CultureInfo.InvariantCulture);
  51. participantInformation = participantinfo.ParticipantApptendanceDetails.Copy();
  52. this.headerControl.lblTimeLimit.Visible = false;
  53. this.lblPresent.Text = /*Properties.Resources.AttendanceRegistrationTxtPresent*/ "Зарегестрировано:" + " " + participantinfo.ParticipantApptendanceDetails.Select("Attendance_Status = 'true'").Length.ToString();
  54. double kv_pres = Convert.ToDouble(participantinfo.ParticipantApptendanceDetails.Select("Attendance_Status = 'true'").Length.ToString());
  55. double kv_abs = Convert.ToDouble(participantinfo.ParticipantApptendanceDetails.Select("Attendance_Status = 'false'").Length.ToString());
  56. this.lblAbsent.Text = "Присутствуют:" + " " + Convert.ToString(kv_pres + kv_abs);
  57. }
  58. }
  59. this.dgvAttendanceRegistration.DataSource = participantInformation;
  60. while (dgvAttendanceRegistration.Rows.Count > 10)
  61. {
  62. dgvAttendanceRegistration.Rows.RemoveAt(10);
  63. }
  64. foreach (DataGridViewRow dgvRow in dgvAttendanceRegistration.Rows)
  65. {
  66. if (dgvRow.Cells["Attendance_Status"].Value.ToString() == "true")
  67. {
  68. dgvRow.DefaultCellStyle.ForeColor = Color.Green;
  69. }
  70. else if (dgvRow.Cells["Attendance_Status"].Value.ToString() == "false")
  71. {
  72. dgvRow.DefaultCellStyle.ForeColor = Color.Red;
  73. }
  74. }
  75. if (this.dgvAttendanceRegistration.ColumnCount > 0)
  76. {
  77. if (this.dgvAttendanceRegistration.Columns.Contains("Participant_Id"))
  78. {
  79. this.dgvAttendanceRegistration.Columns["Participant_Id"].Visible = false;
  80. }
  81. if (this.dgvAttendanceRegistration.Columns.Contains("Attendance_Status"))
  82. {
  83. this.dgvAttendanceRegistration.Columns["Attendance_Status"].Visible = false;
  84. }
  85. }
  86. this.dgvAttendanceRegistration.Refresh();
  87. }
  88. }
  89. }
  90. public delegate void UpdateHeaderDateAndTimeDelegate();
  91. public void UpdateHeaderDateAndTime()
  92. {
  93. if (this.InvokeRequired)
  94. {
  95. UpdateHeaderDateAndTimeDelegate obj = new UpdateHeaderDateAndTimeDelegate(UpdateHeaderDateAndTime);
  96. this.Invoke(obj);
  97. }
  98. else
  99. {
  100. this.headerControl.lblTime.Text = DateTime.Now.ToShortTimeString().ToString(CultureInfo.InvariantCulture);
  101. }
  102. }
  103.  
  104. private void OnFullScreenClick(object sender, EventArgs e)
  105. {
  106. if (this.miFullScreen.Checked)
  107. {
  108. this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
  109. this.miFullScreen.Checked = false;
  110. }
  111. else if (!this.miFullScreen.Checked)
  112. {
  113. this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
  114. this.WindowState = FormWindowState.Maximized;
  115. this.miFullScreen.Checked = true;
  116. }
  117. }
  118. private void dgvAttendanceRegistration_SelectionChanged(object sender, EventArgs e)
  119. {
  120. if (dgvAttendanceRegistration.SelectedRows.Count > 0)
  121. {
  122. dgvAttendanceRegistration.ClearSelection();
  123. }
  124. }
  125. #endregion
  126. #region Fields
  127. ContextMenu cmIndvResults = new System.Windows.Forms.ContextMenu();
  128. MenuItem miFullScreen = new MenuItem();
  129. #endregion
  130. private void AttendanceRegistrationForm_KeyDown(object sender, KeyEventArgs e)
  131. {
  132. if (e.KeyCode == Keys.Escape)
  133. {
  134. AttendanceRegistrationForm.ActiveForm.Close();
  135. }
  136. }
  137.  
  138. internal static bool Equals()
  139. {
  140. throw new NotImplementedException();
  141. }
  142. }
  143. }

Решение задачи: «Для нестатического поля, метода или свойства требуется ссылка на объект»

textual
Листинг программы
  1.        private void HideLabels()
  2.         {
  3.             this.totalLabel.Visible = false;
  4.             this.totalValuelabel.Visible = false;
  5.             this.notVotedLabel.Visible = false;
  6.             this.notVotedValueLabel.Visible = false;
  7.         }
  8.  
  9.  
  10.         private delegate void UpdateStaticDataDelegate(SMDVotingData votingIndvResults);
  11.        
  12.        
  13.         public void UpdateStaticData(SMDVotingData votingIndvResults)
  14.         {
  15.             if (this.InvokeRequired)
  16.             {
  17.                 UpdateStaticDataDelegate obj = new UpdateStaticDataDelegate(UpdateStaticData);
  18.                 this.Invoke(obj, votingIndvResults);
  19.             }
  20.             else
  21.             {
  22.                 if (votingIndvResults != null)
  23.                 {                    
  24.                     ResetUserInterface();                    
  25.                      if (votingIndvResults.VotingData != null)
  26.                     {
  27.                      
  28.                         if (votingIndvResults.VotingData.RemainingVotingTime <= -1)
  29.                         {
  30.                             this.headerControl.lblTimeLimit.Text = Properties.Resources.VotingResultsTxtTimeLimit + ": NA";
  31.                         }
  32.                         else
  33.                         {
  34.                             TimeSpan votingTimeLimit;
  35.                             votingTimeLimit = new TimeSpan(votingIndvResults.VotingData.RemainingVotingTime * TimeSpan.TicksPerSecond);
  36.                             this.headerControl.lblTimeLimit.Text = Properties.Resources.VotingResultsTxtTimeLimit + ": " + string.Format(System.Globalization.CultureInfo.InvariantCulture, RemainingvotingTimeFormatString, Math.Abs(votingTimeLimit.Minutes), Math.Abs(votingTimeLimit.Seconds));
  37.                         }
  38.                     }
  39.                     HideLabels();
  40.                     if (votingIndvResults.Answers != null)
  41.                     {
  42.                         foreach (AnswerContainer answer in votingIndvResults.Answers)
  43.                         {
  44.                             this.totalLabel.Visible = true;
  45.                             this.totalValuelabel.Visible = true;
  46.                             this.notVotedLabel.Visible = true;
  47.                             this.notVotedValueLabel.Visible = true;
  48.                             ResetUserInterface();
  49.                         }
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.         #region Interim Results
  55.  
  56.         public delegate void AddorUpdateInterimResultsDelegate(SMDVotingData votingIndvResults);
  57.         public void AddOrUpdateInterimResults(SMDVotingData votingIndvResults)
  58.         {
  59.             if (this.InvokeRequired)
  60.             {
  61.                 AddorUpdateInterimResultsDelegate obj = new AddorUpdateInterimResultsDelegate(AddOrUpdateInterimResults);
  62.                 this.Invoke(obj, votingIndvResults);
  63.             }
  64.             else
  65.             {
  66.                 try
  67.                 {
  68.                     if (votingIndvResults != null)
  69.                     {
  70.                         if (votingIndvResults.IndividualResults != null && votingIndvResults.IndividualResults.Count > 0)
  71.                         {
  72.  
  73.                             int ansId = 0;
  74.  
  75.                             IndvResults indvResult = new IndvResults();
  76.                             string participantId = String.Empty;
  77.                             string participantName = String.Empty;
  78.                             string participantGroup = String.Empty;
  79.                             string answer = String.Empty;
  80.  
  81.                             for (int iCount = 0; iCount < votingIndvResults.IndividualResults.Count && iCount < 10; iCount++)
  82.                             {
  83.                                 ansId = votingIndvResults.IndividualResults[iCount].AnswerId;
  84.                                 int ansIndex = votingIndvResults.Answers.FindIndex(delegate(AnswerContainer ansCont) { return ansCont.Id == ansId; });
  85.                                if (ansIndex > -1)
  86.                                 {
  87.                                    
  88.                                     indvResult.Answer = votingIndvResults.Answers[ansIndex].AnswerText;
  89.                                  
  90.                                     indvResultsDataGridView.Rows[ansId].Visible = false;
  91.                                 }
  92.                                 else
  93.                                {
  94.                                     indvResult.Answer = "Not Voted";
  95.  
  96.                                }
  97.                                
  98.                                 indvResult.ParticipantId = votingIndvResults.IndividualResults[iCount].Participant.Id.ToString(CultureInfo.InvariantCulture);
  99.                                 indvResult.ParticipantName = votingIndvResults.IndividualResults[iCount].Participant.ParticipantData.FirstName + " " + votingIndvResults.IndividualResults[iCount].Participant.ParticipantData.LastName;
  100.                                 indvResult.ParticipantGroup = votingIndvResults.IndividualResults[iCount].Participant.Group.Name;
  101.                                
  102.                                
  103.                                 if (indvResultsDataSource.Count > 0  )
  104.                                 {
  105.                                  
  106.                                     var modifyIndvResultList = indvResultsDataSource.Where(x => x.ParticipantId == indvResult.ParticipantId).ToList();
  107.                                     if (modifyIndvResultList.Count > 0)
  108.                                     {
  109.                                      
  110.                                         foreach (var iResult in modifyIndvResultList)
  111.                                         {
  112.                                             indvResultsDataSource.Remove(iResult);
  113.                                        
  114.                                         }
  115.                                         indvResultsDataSource.Add(indvResult);
  116.                                     }
  117.                                    else
  118.                                     {
  119.                                         indvResultsDataSource.Add(indvResult);
  120.                                     }
  121.                                 }
  122.                                  
  123.                                 else if (indvResultsDataSource.Count == 0)
  124.                                 {
  125.                                     indvResultsDataSource.Add(indvResult);
  126.                                 }
  127.                             }
  128.                         }
  129.                     }
  130.                     indvResultsBindingSource.DataSource = indvResultsDataSource;
  131.                     UpdateGridViewImage();
  132.                     UpdateTotalResults(votingIndvResults);
  133.  
  134.                 }
  135.                 catch (Exception)
  136.                 {
  137.  
  138.                 }
  139.             }
  140.         }
  141.  
  142.         private void indvResultsDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
  143.         {
  144.             UpdateGridViewImage();
  145.         }
  146.         #endregion
  147.  
  148.         private delegate void UpdateCaptionOfControls(Control c, string str);
  149.  
  150.         private void UpdateCaptionOfControl(Control cntr, string value)
  151.         {
  152.             if (!IsDisposed)
  153.             {
  154.                 if (cntr.InvokeRequired)
  155.                 {
  156.                     Invoke(new UpdateCaptionOfControls(UpdateCaptionOfControl), cntr, value);
  157.                 }
  158.                 else
  159.                 {
  160.                     cntr.Text = value;
  161.                 }
  162.             }
  163.         }
  164.  
  165.         private delegate void UpdateDataSource(DataGridView ctrl, DataTable source);
  166.  
  167.         private void UpdateDataSourceOfGrid(DataGridView ctrl, DataTable source)
  168.         {
  169.             if (!IsDisposed)
  170.             {
  171.                 if (ctrl.InvokeRequired)
  172.                 {
  173.                     Invoke(new UpdateDataSource(UpdateDataSourceOfGrid),indvResultsDataGridView, source);
  174.                 }
  175.                 else
  176.                 {
  177.                     ctrl.DataSource = source;
  178.                 }
  179.             }
  180.         }
  181.  
  182.         private delegate void UpdateDatgridView(DataGridView ctrl);
  183.      
  184.         private void UpdateDataGird(DataGridView ctrl)
  185.         {
  186.             if(!IsDisposed)
  187.             {
  188.                 if(ctrl.InvokeRequired)
  189.                 {
  190.                     Invoke(new UpdateDatgridView(UpdateDataGird), indvResultsDataGridView);
  191.                 }
  192.                 else
  193.                 {
  194.                     ctrl = indvResultsDataGridView;
  195.                 }
  196.             }
  197.         }
  198.  
  199.         private void indvResultsDataGridView_SelectionChanged(object sender, EventArgs e)
  200.         {
  201.             if (indvResultsDataGridView.SelectedRows.Count > 0)
  202.             {
  203.                 indvResultsDataGridView.ClearSelection();
  204.             }
  205.         }
  206.  
  207.         public delegate void UpdateVotingRemainingTimeDelegate(int remainingVotingTime);
  208.  
  209.         public void UpdateRemainingVotingTime(int remainingVotingTime)
  210.         {
  211.             if (this.InvokeRequired)
  212.             {
  213.                 UpdateVotingRemainingTimeDelegate obj = new UpdateVotingRemainingTimeDelegate(UpdateRemainingVotingTime);
  214.                 this.Invoke(obj,remainingVotingTime);
  215.             }
  216.             else
  217.             {
  218.                // this.headerControl.lblDate.Text = DateTime.Now.ToShortDateString().ToString(CultureInfo.InvariantCulture);
  219.                 this.headerControl.lblTime.Text = DateTime.Now.ToShortTimeString().ToString(CultureInfo.InvariantCulture);
  220.                 if (votingResultsData != null)
  221.                 {
  222.                     TimeSpan votingTimeLimit;
  223.                     if (votingResultsData.VotingData != null)
  224.                     {
  225.                         if (votingResultsData.VotingData.RemainingVotingTime <= -1)
  226.                         {
  227.                             this.headerControl.lblTimeLimit.Text = Properties.Resources.VotingResultsTxtTimeLimit + ": NA";
  228.                         }
  229.                         else
  230.                         {
  231.                             votingResultsData.VotingData.RemainingVotingTime = remainingVotingTime;
  232.                             votingTimeLimit = new TimeSpan(votingResultsData.VotingData.RemainingVotingTime * TimeSpan.TicksPerSecond);
  233.                             this.headerControl.lblTimeLimit.Text = Properties.Resources.VotingResultsTxtTimeLimit + ": " + string.Format(System.Globalization.CultureInfo.InvariantCulture, RemainingvotingTimeFormatString, Math.Abs(votingTimeLimit.Minutes), Math.Abs(votingTimeLimit.Seconds));
  234.                         }
  235.                     }
  236.                 }
  237.             }
  238.         }
  239.  
  240.         public delegate void UpdateHeaderDateAndTimeDelegate();
  241.         public void UpdateHeaderDateAndTime()
  242.         {
  243.             if (this.InvokeRequired)
  244.             {
  245.                 UpdateHeaderDateAndTimeDelegate obj = new UpdateHeaderDateAndTimeDelegate(UpdateHeaderDateAndTime);
  246.                 this.Invoke(obj);
  247.             }
  248.             else
  249.             {
  250.              
  251.                 this.headerControl.lblTime.Text = DateTime.Now.ToShortTimeString().ToString(CultureInfo.InvariantCulture);
  252.             }
  253.         }
  254.              
  255.  
  256.         #endregion
  257.  
  258.         #region Properties
  259.         /// <summary>
  260.         /// Object to hold the voting data.
  261.         /// </summary>
  262.         public SMDVotingData VotingIndvResults
  263.         {
  264.             get
  265.             {
  266.                 return votingResultsData;
  267.             }
  268.             set
  269.             {
  270.                 votingResultsData = value;
  271.             }
  272.         }
  273.  
  274.         public DataTable DtIntermediateIndvResults
  275.         {
  276.             get
  277.             {
  278.                 return dtInterimIndvResults;
  279.             }
  280.             set
  281.             {
  282.                 dtInterimIndvResults = value;
  283.             }
  284.         }
  285.  
  286.         public BindingList<IndvResults> IndvResultsDataSource
  287.         {
  288.             get
  289.             {
  290.                 return indvResultsDataSource;
  291.             }
  292.             set
  293.             {
  294.                 IndvResultsDataSource = value;
  295.             }
  296.         }
  297.  
  298.         #endregion
  299.  
  300.         #region Fields
  301.         const string RemainingvotingTimeFormatString = "{0:00}:{1:00}";
  302.         private BindingList<IndvResults> indvResultsDataSource = new BindingList<IndvResults>();
  303.         /// <summary>
  304.         /// A datatable to hold the interim individual Voting results.
  305.         /// </summary>
  306.         DataTable dtInterimIndvResults;
  307.  
  308.         SMDVotingData votingResultsData;
  309.         /// <summary>
  310.         /// A datatable to hold the individual Voting results.
  311.         /// </summary>
  312.        
  313.         ContextMenu cmIndvResults = new System.Windows.Forms.ContextMenu();
  314.         MenuItem miFullScreen = new MenuItem();
  315.         #endregion
  316.  
  317.      
  318.  
  319.         private void IndividualResults_KeyDown(object sender, KeyEventArgs e)
  320.         {
  321.             if (e.KeyCode == Keys.Escape)
  322.             {
  323.                 IndividualResults.ActiveForm.Close();
  324.             }
  325.         }
  326.  }
  327.     public class IndvResults : INotifyPropertyChanged
  328.     {
  329.         string participant_Id;
  330.         string answer;
  331.         string participant_Name;
  332.         string participant_Group;
  333.  
  334.         #region Properties
  335.  
  336.         public event PropertyChangedEventHandler PropertyChanged;
  337.  
  338.         private void NotifyPropertyChanged(string name)
  339.         {
  340.             if (PropertyChanged != null)
  341.                 PropertyChanged(this, new PropertyChangedEventArgs(name));
  342.         }
  343.  
  344.         public string ParticipantId
  345.         {
  346.             get
  347.             {
  348.                 return participant_Id;
  349.  
  350.             }
  351.             set
  352.             {
  353.                 participant_Id = value;
  354.                 this.NotifyPropertyChanged("ParticipantId");
  355.             }
  356.         }
  357.  
  358.         public string Answer
  359.         {
  360.             get
  361.             {
  362.                 return answer;
  363.             }
  364.             set
  365.             {
  366.                 answer = value;
  367.                 this.NotifyPropertyChanged("Answer");
  368.             }
  369.         }
  370.  
  371.         public string ParticipantName
  372.         {
  373.             get
  374.             {
  375.                 return participant_Name;
  376.             }
  377.             set
  378.             {
  379.                 participant_Name = value;
  380.                 this.NotifyPropertyChanged("ParticipantName");
  381.             }
  382.         }
  383.         public string ParticipantGroup
  384.         {
  385.             get
  386.             {
  387.                 return participant_Group;
  388.             }
  389.             set
  390.             {
  391.                 participant_Group = value;
  392.                 this.NotifyPropertyChanged("ParticipantGroup");
  393.             }
  394.         }
  395.         #endregion
  396.     }
  397. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 4.167 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы