Home > Software engineering >  C# How to subscribe to a UserControl event / UserControl has no instance name
C# How to subscribe to a UserControl event / UserControl has no instance name

Time:10-14

I created a UserControl that displays data from a mySQL database(TaskSubject,Date,time).

This UserControl will be created multiple times, based on the amount of tasks.

I am creating the UserControl like this:

        taskSubjectPanel.Controls.Clear();
        DataTable taskdata = new DataTable();
        sql.Connect("JonasW");
        taskdata = sql.GetTasks(username);
        sql.Disconnect();

        if(taskdata.Rows.Count>0)
        {
            for (int i = 0; i < taskdata.Rows.Count; i  )
            {
                taskSubjectPanel.Controls.Add(new TaskSubject(taskdata.Rows[i][0].ToString(),
                                                              taskdata.Rows[i][1].ToString(),
                                                              taskdata.Rows[i][2].ToString(),
                                                              taskdata.Rows[i][3].ToString(),
                                                              taskdata.Rows[i][4].ToString(),
                                                              taskdata.Rows[i][5].ToString(),
                                                              taskdata.Rows[i][6].ToString()));
            }
        }
        taskSubjectPanel.Refresh();

It gets added to a flowlayoutpanel. I created a public event and a public datatable i want to have acces to when UserControl gets Clicked:

        public event EventHandler TaskSubjectClick;
        public DataTable taskdata;

Thats where the public event gets triggered:

        private void RedirectMouseClick(object sender, EventArgs e)
        {
           sql.Connect("JonasW");
           taskdata = sql.GetTaskData(absenderSQL, empfaengerSQL, subjectText.Text, 
           messageSQL, 
           dateText.Text, timeText.Text, finishedSQL);
           sql.Disconnect();
           this.TaskSubjectClick(this, e);
        }

Because it has no name, how do i acces the event and datatable ?.

CodePudding user response:

To create a custom event:

public delegate void TaskSubjectClick(DataTable taskdata);/*<- Put all data you want to pass here*/
public event TaskSubjectClick TaskSubjectClickEvent;

To call the event you have to use invoke:

TaskSubjectClickEvent.Invoke(yourdatatable); //Invoke the event and add your data you want to pass

In your Mainform you have to add the event as following:

yourUserControl.TaskSubjectClickEvent  = MainForm_TaskSubjectClickEvent;
  • Related