2

I create a FaceDetectionEvent which is a user control and try to add it in windows form (still in the same project). But it keeps showing this error: enter image description here

This is the FaceDetectionEvent code:

 public partial class FaceDetectionEvent : UserControl
    {
        private System.Timers.Timer tListener;
        private MySQL_DataAccess da = new MySQL_DataAccess();
        private int iCurrentStatusIndex_ = 0;
        private List<DataRow> lstFaceDetectionEvent = new List<DataRow>(20);
        private ImageList cropImageList = new ImageList();


        public FaceDetectionEvent()
        {
            InitializeComponent();
            CreateColumns();
            GetLastTwentyEvent();

            tListener = new System.Timers.Timer(1000);
            tListener.Elapsed += new System.Timers.ElapsedEventHandler(tListener_Elapsed);
            tListener.Start();
        }

        public void GetLastTwentyEvent()
        {
            string strSQL = string.Format("SELECT * FROM av_status_log AS A LEFT JOIN avmediaserver AS B ON A.device_id=B.DeviceId "
                                        + "LEFT JOIN privilege_device AS C ON A.device_id = C.device_id "
                                        + "LEFT JOIN privilege_device_group AS D ON C.device_group_id = D.device_group_id "
                                        + "WHERE event_type_id = 8 ORDER BY A.db_time DESC LIMIT 20");
            DataTable dt = da.GetInfoData(strSQL).Tables[0];
            if (dt.Rows.Count > 0)
                iCurrentStatusIndex_ = Convert.ToInt32(dt.Rows[0]["rowid"]);

            foreach (DataRow dr in dt.Rows)
            {
                lstFaceDetectionEvent.Add(dr);
                string strCroppedImage = GetCropImageBase64String(dr["memo"].ToString());
                cropImageList.Images.Add(Base64ToImage(strCroppedImage));
            }

            ShowFDEvent();
        }

        void tListener_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string strSQL = string.Format("SELECT * FROM av_status_log AS A LEFT JOIN avmediaserver AS B ON A.device_id=B.DeviceId "
                                        + "LEFT JOIN privilege_device AS C ON A.device_id = C.device_id "
                                        + "LEFT JOIN privilege_device_group AS D ON C.device_group_id = D.device_group_id "
                                        + "WHERE A.rowid > {0} AND event_type_id = 8 ORDER BY A.db_time DESC", iCurrentStatusIndex_.ToString());
            DataTable dt = da.GetInfoData(strSQL).Tables[0];

            if (dt.Rows.Count > 0)
                iCurrentStatusIndex_ = Convert.ToInt32(dt.Rows[0]["rowid"]);

            if (lstFaceDetectionEvent.Count >= 20)
            {
                lstFaceDetectionEvent.RemoveRange(0, dt.Rows.Count);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cropImageList.Images.RemoveAt(i);
                }
            }

            foreach (DataRow dr in dt.Rows)
            {
                lstFaceDetectionEvent.Add(dr);
                string strCroppedImage = GetCropImageBase64String(dr["memo"].ToString());
                cropImageList.Images.Add(Base64ToImage(strCroppedImage));
            }

            ShowFDEvent();
            this.Refresh();
        }

        public string GetCropImageBase64String(string pStrMemo)
        {
            XElement doc = XElement.Parse(pStrMemo);
            string strCropImage = doc.Element("cropImage").Value;
            return strCropImage;
        }

        public Image Base64ToImage(string base64String)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            return image;
        }

        private void CreateColumns()
        {
            ColumnHeader cropImageHeader = new ColumnHeader();
            cropImageHeader.Text = "Crop Image";
            cropImageHeader.Width = 150;
            FDEventlistView.Columns.Add(cropImageHeader);

            ColumnHeader timestampHeader = new ColumnHeader("Event Time");
            timestampHeader.Text = "Event Time";
            timestampHeader.Width = 150;
            FDEventlistView.Columns.Add(timestampHeader);

            ColumnHeader deviceNameHeader = new ColumnHeader("Device Name");
            deviceNameHeader.Text = "Size";
            deviceNameHeader.Width = 80;
            FDEventlistView.Columns.Add(deviceNameHeader);
        }

        private void ShowFDEvent()
        {
            FDEventlistView.Items.Clear();
            FDEventlistView.BeginUpdate();
            int i = 0;
            foreach (DataRow dr in lstFaceDetectionEvent)
            {
                ListViewItem item = new ListViewItem();
                item.ImageIndex = i;

                ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem();
                subitem.Text = dr["status_time"].ToString();
                item.SubItems.Add(subitem);

                subitem = new ListViewItem.ListViewSubItem();
                subitem.Text = dr["device_name"].ToString();
                item.SubItems.Add(subitem);

                FDEventlistView.Items.Add(item);

                i++;
            }

            FDEventlistView.EndUpdate();
        }
    }

Do you have any idea why?

3
  • On which line you get this exception? Did you debug your code? Commented Oct 3, 2014 at 8:21
  • I think this could happen due to two things .. 1. If your code is using more than one config file and at run time it fails to merge these. 2. or the code is not able to find any particular dll at run time. for this reason I suggest copy all the dll files that currently your program needs to the bin folder and try running and see .. Commented Oct 3, 2014 at 8:35
  • if I add the usercontrol programmatically, it could work. And I already copy all dll files to the bin folder Commented Oct 3, 2014 at 8:37

3 Answers 3

4

Code in your UserControl will run at design time as well. A feature that provides the WYSIWIG behavior of a control when you drop it on a form with the designer. But certainly can be troublesome, in this case you do not want to query the dbase, no chance that you'll be able to find the correct connection string when the control is loaded in Visual Studio instead of your program. Simply skipped by using the DesignMode property:

    public FaceDetectionEvent()
    {
        InitializeComponent();
        tListener = new System.Timers.Timer(1000);
        tListener.Elapsed += new System.Timers.ElapsedEventHandler(tListener_Elapsed);
        if (!this.DesignMode) {
            CreateColumns();
            GetLastTwentyEvent();
            tListener.Start();
        }
    }

You may need to insert the DesignMode test in other places in your code, like Paint and Load event handlers.

Do note how debugging such design-time only exceptions can be difficult, the message box isn't big enough to show you the stack trace. In the really hard cases you may need to debug Visual Studio itself so you can see the exception. Start another instance of VS and use Tools + Attach to Process to attach the debugger to the 1st instance. Debug + Exceptions, tick the Thrown checkbox to automatically break when the exception is thrown.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't think the problem is about UserControl. To prove this, create a new user control, this time not programmatically -> Add New and choose UserControl. Delete the FaceDetectionEvent Control from the MainForm for now, then add the newly created UserControl and see if the error shows up again. If it does please share the content of the StackTrace.

Comments

0

I've had this same issue trying to add my user controls to a form by dragging it from the tool box. It may seem obvious, but my issues involved having parameters in the constructor that were intended to be passed at run-time if the control was added programatically...

So this code will cause the error. To avoid it don't have arguments in the constructor.

public ucMyControl(string title)
{
    InitializeComponent();
    groupBox1.Text = title;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.