一种使用usercontrol从父窗体访问类/方法的方法

时间:2017-04-06 08:10:23

标签: c# user-controls

我希望获得一些建议或可能的解决方案,以便从parentFormuserControl访问一个类或方法。

我想重复使用loadquizes() dataGrid,只是为了使用同一表单上的gradingSheetuserControl表单重新加载Mainform(Form) |_Gradingsheet(MDIchild/Also a Form) |_mypanel(inside the Gradingsheet) |_updatequizes(usercontrol)

我的项目结构是:

GradingSheet

userControl代码调用private void updateQuizToolStripMenuItem_Click(object sender, EventArgs e) { quiz = new UpdateQuizes(); quiz.lrnLbl.Text = MelrnLbl.Text; quiz.nameLbl.Text = MEnameLbl.Text; quiz.quartervar.Text = quartervar.Text; quiz.GradeLbl.Text = GradeLbl.Text; quiz.subjLbl.Text = subjLbl.Text; quiz.yearLbl.Text = yearLbl.Text; UserControlPanel.Controls.Clear(); UserControlPanel.Controls.Add(quiz); }

UserControl

void insertQuiz() { using (MySqlConnection conn = new MySqlConnection(myConnection)) { string query = "UPDATE GimenezSystem.quizes SET Q"+(quizcombo.SelectedIndex + 1) + " =?newval WHERE Year=?year and GradeLevel=?glevel and Subject=?subj and Quarter =?qtr and LRN =?LRN"; conn.Open(); using (MySqlCommand cmd = new MySqlCommand(query, conn)) { try { cmd.Parameters.AddWithValue("?LRN", lrnLbl.Text); //cmd.Parameters.AddWithValue("?quiz", quiz); cmd.Parameters.AddWithValue("?newval", NewVal.Text); cmd.Parameters.AddWithValue("?year", yearLbl.Text); cmd.Parameters.AddWithValue("?glevel", GradeLbl.Text); cmd.Parameters.AddWithValue("?subj", subjLbl.Text); cmd.Parameters.AddWithValue("?qtr", quartervar.Text); cmd.ExecuteNonQuery(); GradingSheet gr = GradingSheet.ActiveForm as GradingSheet; gr.loadquizes();//here it gives me an error of object is not set for reference of instance or something like that T.T } catch (Exception ex) { MessageBox.Show("error" + ex); } } conn.Close(); } }

gsub

1 个答案:

答案 0 :(得分:0)

如果你真的想重复使用多个方法的方法,那么考虑在一个单独的类中实现该方法,并在你想要的任何一个或用户控件中使用它,而不是在Form或{{ 1}}。下面的代码行是问题。

UserControl

Instread将它放在一个单独的类中,如

          GradingSheet gr = GradingSheet.ActiveForm as GradingSheet;
                gr.loadquizes();//he