mardi 21 avril 2015

No overload for "method" matches delegate 'System.EventHandler'?

private async void submitRequestButton_Click(DateTime dateFormat, DateTime startFormat, DateTime endFormat, EventArgs e)
    {
        ParseObject request = new ParseObject("Shifts");
        request["Name"] = ParseUser.CurrentUser.Username;
        request["Shift"] = shiftBox.Text;
        request["Rental"] = rentalBox.Checked;
        request["Location"] = locationBox.Text;
        request["Date"] = dateFormat.ToString("MMMM dd, yyyy");
        request["startTime"] = startFormat.ToString("t", CultureInfo.CreateSpecificCulture("en-us"));
        request["endTime"] = endFormat.ToString("t", CultureInfo.CreateSpecificCulture("en-us"));

        await request.SaveAsync();
    }

    private DateTime datePicker_ValueChanged(DateTime dateFormat, EventArgs e)
    {
        dateFormat = datePicker.Value;

        return dateFormat;
    }

    private DateTime startTimePicker_ValueChanged(DateTime startFormat, EventArgs e)
    {
        startFormat = startTimePicker.Value;

        return startFormat;
    }

    private DateTime endTimePicker_ValueChanged(DateTime endFormat, EventArgs e)
    {
        endFormat = endTimePicker.Value;

        return endFormat;
    }

I don't understand why I am getting this error for methods 2, 3 and 4.

No overload for "method" matches delegate 'System.EventHandler'?

If you need to see more code just let me know. I'm pretty sure everything is hooked up properly.

It looks like the error is coming from: this.datePicker.ValueChanged += new System.EventHandler(this.datePicker_ValueChanged); (the same goes for the other 2 methods).

Please help!

DesignSurface: Can't delete controls

I'm currently working on a project involving DesignSurfaces.

In the program load event, I load a form with 3 textboxes, 3 labels and a button. To manage these controls, I have a ContextMenuStrip with MenuItems containing the StandardCommands Cut, Copy, Paste and Delete. However, when I try any of these actions, It'll throw an InvalidOperationException which says something like "The inherited component 'textBox1' cannot be deleted" (Unfortunately, I don't have the exception message in english, but through googling I found that it might be this one: "Cannot remove or destroy inherited component") If I add a control runtime and try to delete it, everything works fine (Cut, Copy, Paste too).

Here's the code for the ContextMenuStrip:

public void ShowContextMenu( CommandID menuID, int x, int y ) {
            ContextMenu contextMenu = new ContextMenu();

            MenuCommand command = FindCommand( StandardCommands.Cut );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Cut", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }
            command = FindCommand( StandardCommands.Copy );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Copy", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }
            command = FindCommand( StandardCommands.Paste );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Paste", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }
            command = FindCommand( StandardCommands.Delete );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Delete", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }

            DesignSurface surface = (DesignSurface) _serviceProvider;
            Control viewService = (Control) surface.View;

            if( viewService != null ) {
                contextMenu.Show( viewService, viewService.PointToClient( new Point( x, y ) ) );
            }
        }


private void OnMenuClicked( object sender, EventArgs e ) {
            MenuItem menuItem = sender as MenuItem;
            if( menuItem != null && menuItem.Tag is MenuCommand ) {
                MenuCommand command = menuItem.Tag as MenuCommand;
                command.Invoke();
            }
        }

I can't figure out what the problem is here.

Did someone here experience a similiar issue? Or any ideas on how to solve this?

TileItem Click Event not working properly?

I have a TileItem in a tilecontrol (DevExpress). On click this method is fired

private void tileItem1_ItemClick_1(object sender, DevExpress.XtraEditors.TileItemEventArgs e)
        {
            if (GetForegroundWindow() == Process.GetCurrentProcess().MainWindowHandle)
            {
                MessageBox.Show("It is focused!");
                //do some magic here
            }
            else
            {
                MessageBox.Show("It is not focused!");
                this.Activate();
            }
        }

My problem is that even if my form is not focused, it will think that it is focused and always triger the first condition of the if statement. I want to activate the window when the tileitem is clicked IF the window is not focused. Isn't this the proper way to do it? What i am thinking is that the method is triggered after the mouse is released so the window has already taken focus by that time. If this is the problem then which is the solution to achieve what i am trying to do?

Thanks is advance.

Combobox displaying list instance instead of the actual value names

I am populating a combobox with data from database. The data is being stored in a list. When I run the form, the combobox displays the right amount of GroupPlayers i.e. 2 but doesn't actually display the name of these groups, instead it displays the list (i think it's called, correct me if i am wrong) instance i.e. group.

Main form:

    public void Groups() {
        var smallGroups = new List<GroupsPlayers>();

        //sql connections query etc etc is here 

        while(rd.Read())
        {
            var currentPlayer = new GroupsPlayers() {
                GroupID = rd["GroupID"].ToString(),
                GroupName = rd["GroupName"].ToString(),

            };

            smallGroups.Add(currentPlayer);
        }

        if(userResponse == DialogResult.Yes)
        {
            UpdatePlayer frmPlayers = new UpdatePlayer(smallGroups);
        }
    } 

UpdatePlayer form

 public class GroupsPlayers
    {
        public string GroupID { get; set; }
        public string GroupName { get; set; }
    }


List<GroupsPlayers> _GroupPlayers;
UpdatePlayer (List<GroupsPlayers> GroupPlayers)
{
    _GroupPlayers = GroupPlayers; 
}

private void BindCb()
        {
            cb.DataSource = _GroupPlayers;
            cb.DisplayMember = "GroupName";

        }

Also, when I use cb.ValueMemeber = "GroupID"; I get the error

Cannot bind to the new display member

In C#, WebBrowser1,DocumentComplete fires 4 times

I have a button that has the following code

 webbrowser1.Navigate(testURL);

In my

 private void webbrowser1_Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
       if (e.Url.Equals(psyncBrowser.Url))
        {
            Console.WriteLine("Now it is really done");
            MessageBox.Show("Loaded " + psyncBrowser.Url);
            webbrowser1.Stop();
        }
 }

I get a console message with the message 4 times!!! HOw can I stop this from happening?

Mouse pointer position when pointer is not on winform

I'm able to get the mouse position when it is within the form. Here is my code-

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    lblXPosition.Text = MousePosition.X.ToString();
    lblYPosition.Text = MousePosition.Y.ToString();
}

But it does not work when the pointer is outside the form. Any suggestion?

Disabling scrollbar of Winform control inside WPF control

I have a WindowsFormsHost, with a Winform control in it, inside a WPF Tab item.

I've set the scrollbar to 'Hidden' on the Tab Control, the Tab Item itself, the WindowsFormsHost AND the Winform control inside the Host.

The scrollbars are still there, so at this point I'm not sure where they're coming from. I've also disabled the scrollbar on the entire window itself.

I have ScrollViewer.HorizontalScrollBarVisibility="Hidden" set on all the aforementioned controls.

Upload image from Bitmap to server as png

I am trying to upload a System.Drawing.Bitmap variable I have in my C# winform application as a .png image on my server. Right now I know how to save a Bitmap as a .png file and then upload it to my server.

//Save bitmap variable as .png
bitmap.Save("img_1.png", ImageFormat.Png);

And then upload that to my server like so:

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential("FTP_username",
        "FTP_password");
    client.UploadFile("http://ift.tt/1QgnQBz",
        "img_1.png");
}

How could I upload the Bitmap bitmap variable as a .png file on my server directly, without having to save it as a new .png file locally first ?

SetSystemCursor() for multiple cursors behavior

I am trying to change multiple cursors to Cross cursor. This is the code I am using for that matter:

[DllImport("user32.dll")]
static extern bool SetSystemCursor(IntPtr hcur, uint id);
[DllImport("user32.dll")]
static extern IntPtr LoadCursor(IntPtr hInstance, int lpCursorName);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SystemParametersInfo(UInt32 uiAction, 
    UInt32 uiParam, String pvParam, UInt32 fWinIni);

//Normal cursor
private static uint OCR_NORMAL = 32512;
//The text selection (I-beam) cursor.
private static uint OCR_IBEAM = 32513;
//The cross-shaped cursor.
private static uint OCR_CROSS = 32515;

Then I use these two functions I made:

static public void ChangeCursors() {
    SetSystemCursor(LoadCursor(IntPtr.Zero, (int)OCR_NORMAL), OCR_CROSS);
    SetSystemCursor(LoadCursor(IntPtr.Zero, (int)OCR_IBEAM), OCR_CROSS);
}

static public void RevertCursors() {
    SystemParametersInfo(0x0057, 0, null, 0);
}

If I just use SetSystemCursor(LoadCursor(IntPtr.Zero, (int)OCR_NORMAL), OCR_CROSS);, everything works fine. The Normal cursor gets replaced by Cross cursor.

My problem is when I try to change multiple cursors to Cross cursor. If I call ChangeCursors(), the expected result would be Normal cursor AND I-beam cursor gets replaced by Cross cursor. But the result is something really weird.

When the software starts depending on the current state of the cursor when the program started, the following strange things happen:

  • If cursor was Normal when the software started, it changes to Cross (that's good). Also, I-beam is replaced with Normal (that's bad, it should be Cross).
  • If cursor was I-beam when the software started, it stays I-beam(that's bad, because it should be Cross). Then, by hovering over to where previously the cursor should be Normal it is now Cross (that's good). Then, if I hover over to where the cursor was I-beam 1 second ago, it magically changes to Normal (that's weird) and stays that way.

So, my question is, how can I change 2 or more Cursors to Cross cursor, using SetSystemCursor() ?

How to pass a var list to another winform c#

Let's say I have this code. How can I pass smallGroups to UpdatePlayer form. I need to be able to use the data generated to the var list and use it in UpdatePlayer to populate combobox? Could someone help me please

    public class GroupsPlayers
    {
        public string GroupID;
        public string GroupName;
    }

public void Groups() {
    var smallGroups = new List<GroupsPlayers>();


    while(rd.Read())
    {
        var currentPlayer = new GroupsPlayers() {
            GroupID = rd["GroupID"],
            GroupName = rd["GroupName"]
        };

        smallGroups.Add(currentPlayer);
    }

    string msgBoxMsg = string.Format("There are {0} groups with fewer than 3 players. Do you want to add new players to the group?", smallGroups.Count);

    MessageBoxResult userResponse = MessageBox.Show(msgBoxMsg, "Groups Manager", MessageBoxButtons.YesNo);

    if(userResponse == DialogResult.Yes)
    {
        UpdatePlayer frmPlayers = new UpdatePlayer(this, smallGroups);
    }
}

how to populate textbox with new Row ID in windows form

I'm creating a windows form and currently in the process of creating the "create member" form.

Now i wish to show to the user inputting data what the new members ID will be. So i thought of trying to show the new row ID within a text box.

I've tried to attempt it below but having difficulty getting the result from the sqlCommand. Or maybe im going the wrong way around doing it ha

Can anyone see how i can apply the id upon load?

    private void frmAddMember_Load(object sender, EventArgs e)
    {
        using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
        {
            connection.Open();
            using (var cmd = new SqlCommand("SELECT * FROM Users WHERE UserID=(SELECT MAX(UserID) FROM Users", connection))
            {
                //cmd.Parameters.Add("@MYVALUE", SqlDbType.VarChar).Value = comboBox1.Text;
                SqlDataReader re = cmd.ExecuteReader();

                if (re.Read())
                {
                    txtMemberId.Text = // result from the SQLCommand but i dont know how to get it

Adding a comboBoxcolumn to datatable in winforms

Question How can I add a comboBoxcolumn to a dataTable and not just the grid? I tried setting the "Connector Name" column to be a comboboxcolumn , but apparently I'm not doing it right.

What I have (snippet):

  if (_DtMain.Columns.Count == 0)
            {

                var cols = new List<DataColumn>();
                cols.Add(new DataColumn("PocketName", typeof(string)));
                cols.Add(new DataColumn("KeyIndex", typeof(string)));
                cols.Add(new DataColumn("SortOrder", typeof(int)));
                cols.Add(new DataColumn("ConnectorName", typeof(DataGridViewComboBoxColumn )));
                _DtMain.Columns.AddRange(cols.ToArray());
                dataGridView1.DataSource = _DtMain.DefaultView;

            }

Why is program output different when invoked from Console application and from Windows Forms application

I am a novice developer trying to develop framework and some internal tools for UI automation.

I have some code in Helpers class which basically provides functionality to check and prepare expected directory structure, copy some files from a network folder, start a couple of Java applications (Selenium hub and node, for those interested) etc. All these methods accept an IProgress in order to be able to report back the progress, exceptions, errors etc.

I have written one console application and one Windows Forms application doing exactly the same thing but to suit different audience (Devs vs BAs). However, the behaviour and output from the Helpers class methods is different when invoked from Console app vs Windows Forms app. My question is whether this is expected. If so, how do I resolve this issue? If not, any pointers to what I am doing wrong would be greatly appreciated. Code below.

public class Helpers
        {
            public static void StartHub(string[] hubParams, IProgress<string> progress)
            {
                try
                {
                    string hubParameters;
                    if (hubParams == null)
                    {
                        hubParameters = String.Empty;
                    }
                    else
                    {
                        hubParameters = String.Join(" ", hubParams);
                        hubParameters = hubParameters.Replace("/", "-");
                    }
                    var hubCommand =
                        String.Format(
                            @"-Xmx1024m -jar C:\Selenium\ServerExecutable\selenium-server-standalone.jar -role hub -log C:\Selenium\_Logs\hub_{0}.log {1}",
                            DateTime.Now.ToString("ddMMMyyyy-HHmmss"), hubParameters).Trim();
                    ExecuteCommand(String.Format(@"{0}\java.exe", GetJavaPath(progress)), progress, hubCommand, false);
                    ExecuteCommand(String.Format("http://{0}:4444/grid/console", Environment.MachineName), progress, hideWindow: false);
                    progress.Report(
                        "Hub started. Please check the opened command window and/or browser window to ensure it started successfully. For logs look in C:\\Selenium\\_Logs folder.");
                }
                catch (Exception e)
                {
                    progress.Report(string.Format("Could not start hub. {0}{1}", e, Environment.NewLine));
                }
            }

            public static void StartNode(NodeOptions nodeParams, IProgress<string> progress)
            {
                try
                {
                    var ieVersion = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Internet Explorer").GetValue("svcVersion").ToString().Split('.')[0];
                    var defaultNodeCommand = String.Format(
                        @"-Xmx512m -jar C:\Selenium\ServerExecutable\selenium-server-standalone.jar -role wd -hub http://{1}/grid/register -log C:\Selenium\_Logs\node_{0}.log -Dwebdriver.chrome.driver=C:\Selenium\chromedriver_win32\chromedriver.exe -Dwebdriver.ie.driver=C:\Selenium\IEDriver_Win32\IEDriverServer.exe",
                        DateTime.Now.ToString("ddMMMyyyy-HHmmss"), nodeParams.Hub);
                    var nodeBrowsers = _BuildBrowsersNodeCommand(nodeParams, ieVersion);
                    string nodeCommand = String.Format("{0}{1}", defaultNodeCommand, nodeBrowsers);
                    ExecuteCommand(String.Format(@"{0}\java.exe", GetJavaPath(progress)), progress, nodeCommand, false);
                    progress.Report(
                        "Node started. Please check the opened command window and/or browser window to ensure it started successfully. For logs look in C:\\Selenium\\_Logs folder." +
                        Environment.NewLine);
                }
                catch (Exception e)
                {
                    progress.Report(string.Format("Could not start node. {0}{1}", e, Environment.NewLine));
                }
            }

            private static string _BuildBrowsersNodeCommand(NodeOptions nodeParams, string ieVersion)
            {
                var nodeBrowsers = new StringBuilder();
                foreach (var browser in nodeParams.BrowsersList)
                {
                    if (browser.ToUpperInvariant() == "IE" || browser.ToUpperInvariant() == "INTERNETEXPLORER")
                    {
                        nodeBrowsers.Append(String.Format(
                            " -browser \"platform=WINDOWS,version={0}Windows7,browserName=internet explorer,maxInstances=1\"",
                            ieVersion));
                    }
                    else
                    {
                        nodeBrowsers.Append(String.Format(
                            " -browser \"platform=WINDOWS,version=Windows7,browserName={0},maxInstances={1}\"",
                            browser, nodeParams.MaxSessions));
                    }
                }
                return nodeBrowsers.ToString();
            }

            public static Process ExecuteCommand(string fileName, IProgress<string> progress, string command = null, bool hideWindow = true)
            {
                if (hideWindow)
                {
                    var processInfo = new ProcessStartInfo(fileName, command)
                    {

                        CreateNoWindow = true,
                        UseShellExecute = false,
                        //WorkingDirectory = "\\",
                        // *** Redirect the output ***
                        RedirectStandardError = true,
                        RedirectStandardOutput = true
                    };

                    var process = new Process { StartInfo = processInfo, EnableRaisingEvents = true };
                    process.ErrorDataReceived += (sender, args) => progress.Report(args.Data);
                    process.OutputDataReceived += (sender, args) => progress.Report(args.Data);
                    var started = process.Start();
                    progress.Report(string.Format("process started: {0}", started));
                    progress.Report(string.Format("process id: {0}", process.Id));
                    progress.Report(string.Format("process start info: {0} {1}", process.StartInfo.FileName, process.StartInfo.UserName));
                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();
                    process.WaitForExit();

                    int ExitCode = process.ExitCode;

                    progress.Report(string.Format("ExitCode: {0}{1}", ExitCode, Environment.NewLine));
                    process.Close();
                    return null;
                }
                else
                {
                    var process = Process.Start(fileName, command);
                    //process.WaitForExit();
                    return process;
                }
            }

            public static string GetJavaPath(IProgress<string> progress)
            {
                var javaPath = Environment.GetEnvironmentVariable("path").Split(';').FirstOrDefault(s => s.Contains("javapath"));
                if (javaPath == default(string))
                {
                    progress.Report(string.Format(@"{0}Java is either not installed on this machine or its path is not set in System environment variable 'Path'. Cannot proceed without Java.{0}", Environment.NewLine));
                    throw new ApplicationException(
                        @"Java is either not installed on this machine or its path is not set in System environment variable 'Path'. Cannot proceed without Java.");
                }
                return javaPath;
            }

            public static void CreateRequiredDirectories(IProgress<string> progress)
            {
                progress.Report(string.Format(@"Checking required folder structure exists...{0}", Environment.NewLine));
                if (!Directory.Exists(@"C:\Selenium"))
                {
                    progress.Report(string.Format(@"C:\Selenium folder doesn't exist on your machine. Creating it now...{0}", Environment.NewLine));
                    Directory.CreateDirectory(@"C:\Selenium");
                    progress.Report(string.Format(@"C:\Selenium folder created successfully{0}", Environment.NewLine));
                }
                if (!Directory.Exists(@"C:\Selenium\_Logs"))
                {
                    progress.Report(string.Format(@"C:\Selenium\_Logs folder doesn't exist on your machine. Creating it now...{0}", Environment.NewLine));
                    Directory.CreateDirectory(@"C:\Selenium\_Logs");
                    progress.Report(string.Format(@"C:\Selenium\_Logs folder created successfully{0}", Environment.NewLine));
                }
                progress.Report(string.Format(@"Required folder structure checked successfully{0}", Environment.NewLine));
            }

            public static void CopyRequiredFiles(IProgress<string> progress, bool hideWindow = false)
            {
                progress.Report(string.Format("Copying latest version of executables...{0}", Environment.NewLine));
                var currentDirectory = Directory.GetCurrentDirectory();
                ExecuteCommand(String.Format(@"{0}\Copy latest Selenium files.bat", currentDirectory), progress, hideWindow: hideWindow);
                progress.Report(string.Format("\r\nLatest version of executables copied successfully{0}", Environment.NewLine));
            }

            public static IEnumerable<string> ParseArguments(string commandLine)
            {
                if (string.IsNullOrWhiteSpace(commandLine))
                    yield break;
                var sb = new StringBuilder();
                bool inQuote = false;
                foreach (char c in commandLine)
                {
                    if (c == '"' && !inQuote)
                    {
                        inQuote = true;
                        continue;
                    }
                    if (c != '"' && !(char.IsWhiteSpace(c) && !inQuote))
                    {
                        sb.Append(c);
                        continue;
                    }
                    if (sb.Length > 0)
                    {
                        var result = sb.ToString();
                        sb.Clear();
                        inQuote = false;
                        yield return result;
                    }
                }
                if (sb.Length > 0)
                    yield return sb.ToString();
            }
        }

My Console App:

public class Program
    {
        private static readonly LauncherOptions Options = new LauncherOptions();
        private static bool _startHub;
        private static bool _startNode;
        private static StringBuilder sb = new StringBuilder();
        private static readonly Action<string> OutputAction = s => Console.WriteLine(s);
        private static readonly Action<string> OutputActionAlter = s => sb.AppendLine(s);
        private static readonly IProgress<string> Progress = new Progress<string>(OutputActionAlter);

public static void Main(string[] args)
        {
            if (Parser.Default.ParseArguments(args, Options))
            {
                _AcknowledgeAndCheckArguments();

            Helpers.CreateRequiredDirectories(Progress);

            Helpers.CopyRequiredFiles(Progress, true);

            if (_startHub)
            {
                Helpers.StartHub(Options.HubParams, Progress);
            }
            if (_startNode)
            {
                var nodeOptions = new NodeOptions();
                Console.WriteLine(nodeOptions.GetUsage());
                Console.WriteLine("Please use above parameters to customise your node. For default node, just press the enter key.");
                var userInput = Console.ReadLine();
                var userInputArgs = Helpers.ParseArguments(userInput);
                Parser.Default.ParseArguments(userInputArgs.ToArray(), nodeOptions);
                Helpers.StartNode(nodeOptions, Progress);
            }
            Console.WriteLine("\r\nPress any key to close the Launcher. For hub and node logs look in C:\\Selenium\\_Logs folder.\r\n");
            var output = sb.ToString();
            Console.ReadKey();
        }
    }

}

My Windows Forms app:

public partial class frmLauncherMain : Form
    {
        private readonly LauncherOptions _options = new LauncherOptions();
        private readonly NodeOptions _nodeOptions = new NodeOptions();
        private readonly List<string> _selectedBrowsers = new List<string>();

        private StringBuilder sb = new StringBuilder();
        private readonly IProgress<string> _progress;

        public frmLauncherMain()
        {
            InitializeComponent();
            cboMaxSessions.SelectedItem = "5";
            chkStartHub.Checked = true;
            chkStartNode.Checked = true;
            _nodeOptions.BrowsersList = new[] { "chrome", "firefox", "ie" };
            _nodeOptions.Hub = "localhost:4444";
            _nodeOptions.MaxSessions = "5";
            txtOutput.Clear();
            Action<string> outputAction = s => txtOutput.InvokeEx(t => t.Text += s);
            Action<string> outputActionAlter = s => sb.AppendLine(s);
            _progress = new Progress<string>(outputActionAlter);
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            txtOutput.Clear();
            //sb.Clear();
            if (txtHubParams.TextLength != 0)
            {
                _options.HubParams = Helpers.ParseArguments(txtHubParams.Text).ToArray();
            }
            if (chkCustomNode.Checked)
            {
                if (_selectedBrowsers.Any())
                {
                    _nodeOptions.BrowsersList = _selectedBrowsers.ToArray();
                }
                else
                {
                    MessageBox.Show("Please select at least one browser.");
                }
                _nodeOptions.Hub = txtHub.Text.Trim();
                _nodeOptions.MaxSessions = string.IsNullOrEmpty(cboMaxSessions.SelectedText) ? "5" : cboMaxSessions.SelectedText;
            }
            Helpers.CreateRequiredDirectories(_progress);

            Helpers.CopyRequiredFiles(_progress, true);

            if (chkStartHub.Checked)
            {
                Helpers.StartHub(_options.HubParams, _progress);
            }
            if (chkStartNode.Checked)
            {
                Helpers.StartNode(_nodeOptions, _progress);
            }
            var output = sb.ToString();
            /* trying another method
            var createDirectoriesTask = new Task(() => Helpers.CreateRequiredDirectories(progress));
            var copyFilesTask = new Task(() => Helpers.CopyRequiredFiles(progress, true));
            var startHubTask = new Task(() => Helpers.StartHub(_options.HubParams, progress));
            var startNodeTask = new Task(() => Helpers.StartNode(_nodeOptions, progress));

            createDirectoriesTask.Start();
            createDirectoriesTask.ContinueWith(delegate { copyFilesTask.Start(); });
            if (chkStartHub.Checked)
            {
                copyFilesTask.ContinueWith(delegate { startHubTask.Start(); });
            }
            if (chkStartNode.Checked)
            {
                startHubTask.ContinueWith(delegate { startNodeTask.Start(); });
            }
             */
            //txtOutput.Text = sb.ToString();
        }

        private void chkChrome_CheckedChanged(object sender, EventArgs e)
        {
            if (chkChrome.Checked)
            {
                _selectedBrowsers.Add("chrome");
            }
        }

        private void chkFirefox_CheckedChanged(object sender, EventArgs e)
        {
            if (chkFirefox.Checked)
            {
                _selectedBrowsers.Add("firefox");
            }
        }

        private void chkIE_CheckedChanged(object sender, EventArgs e)
        {
            if (chkIE.Checked)
            {
                _selectedBrowsers.Add("internet explorer");
            }
        }

        private void chkStartHub_CheckedChanged(object sender, EventArgs e)
        {
            _options.StartHub = chkStartHub.Checked ? "yes" : "no";
        }

        private void chkStartNode_CheckedChanged(object sender, EventArgs e)
        {
            _options.StartNode = chkStartHub.Checked ? "yes" : "no";
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
            Environment.Exit(0);
        }
    }

Output from Console app:

Checking required folder structure exists...

Required folder structure checked successfully

Copying latest version of executables...

process started: True process id: 1196 process start info: D:\Managed\RUN\Source\Main\Automation\Selenium\HubNodeLauncher\SeleniumHubNodeLauncher\bin\Debug\Copy latest Selenium files.bat Deleting existing mappings... z: was deleted successfully.

Mapping network drives... The command completed successfully.

Copying latest Selenium jars... Z:\Hub and Node Executables\Launch Selenium 2 Node.bat Z:\Hub and Node Executables\lessons.txt Z:\Hub and Node Executables__hub parameters.txt Z:\Hub and Node Executables\Launch Selenium 2 Hub.bat Z:\Hub and Node Executables\chromedriver_win32\chromedriver.exe Z:\Hub and Node Executables\chromedriver_win32\chromedriver_win32_2.12.zip Z:\Hub and Node Executables\chromedriver_win32\chromedriver_win32_2.14.zip Z:\Hub and Node Executables\chromedriver_win32\chromedriver_win32_2.9.zip Z:\Hub and Node Executables\chromedriver_win32\current version is 2.14.txt Z:\Hub and Node Executables\IEDriver_Win32\current version is Win32_2.45.0.txt > Z:\Hub and Node Executables\IEDriver_Win32\IEDriverServer.exe Z:\Hub and Node Executables\IEDriver_Win32\IEDriverServer_Win32_2.41.0.exe Z:\Hub and Node Executables\IEDriver_Win32\IEDriverServer_Win32_2.44.0.exe Z:\Hub and Node Executables\IEDriver_x64\Current version is _x64_2.45.0.txt Z:\Hub and Node Executables\IEDriver_x64\IEDriverServer.exe Z:\Hub and Node Executables\IEDriver_x64\IEDriverServer_x64_2.44.0.exe Z:\Hub and Node Executables\NodeConfigs\nodeconfig.json Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Custom Node v2.bat Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Custom Node v3.bat Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Custom Node.bat Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Default Node Using json.bat > Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Default Node.bat Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Win 7 Chrome Firefox Node.bat Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Win 7 IE 11 Node.bat Z:\Hub and Node Executables\NodeConfigs\Selenium 2 Win 8.1 IE 11 Node.bat Z:\Hub and Node Executables\ServerExecutable\current version is -2.45.0.txt Z:\Hub and Node Executables\ServerExecutable\selenium-server-standalone-2.41.0.jar Z:\Hub and Node Executables\ServerExecutable\selenium-server-standalone-2.43.1.jar Z:\Hub and Node Executables\ServerExecutable\selenium-server-standalone-2.44.0.jar Z:\Hub and Node Executables\ServerExecutable\selenium-server-standalone.jar 30 File(s) copied Finished copying latest Selenium jars... All done

ExitCode: 0

Latest version of executables copied successfully

Hub started. Please check the opened command window and/or browser window to ensure it started successfully. For logs look in C:\Selenium_Logs folder.

Node started. Please check the opened command window and/or browser window to ensure it started successfully. For logs look in C:\Selenium_Logs folder.

Output from Windows Forms app:

Checking required folder structure exists...

Required folder structure checked successfully

Copying latest version of executables...

process started: True process id: 13200 process start info: D:\Managed\RUN\Source\Main\Automation\Selenium\HubNodeLauncher\SeleniumHubNodeLauncherUI\bin\Debug\Copy latest Selenium files.bat Deleting existing mappings... z: was deleted successfully.

Mapping network drives... The command completed successfully.

Copying latest Selenium jars... Finished copying latest Selenium jars... All done

ExitCode: 0

Latest version of executables copied successfully

Dead lock with backgroundWorker

I faced with one interesting moment when working with multithreading. I have two threads. In main thread I create layout and add to it control,in second thread I create another control and add to the same layout. It works fine, but second thread works a bit longer then main. So main should wait for second thread.I use for this AutoResetEvent and got DeadLock. Below I describe code what I use:

 private static AutoResetEvent resetEvent = new AutoResetEvent(false);
    private BackgroundWorker backgroundAdvancedViewWorker = new BackgroundWorker();
    private delegate void ShowViewDelegate();

    public void Run()
    {
        MainGeneralReportForm mainForm = ObjectFactory.GetOrCreateView<IMainGeneralReportForm>();
        backgroundSimpleViewWorker.RunWorkerAsync(_mainForm);
        GeneralReportFormatView formatView =
                        ObjectFactory.ShowView<IGeneralReportFormatView>()
        resetEvent.WaitOne();
        DoSomething(advancedSearchView);
    }

    private void backgroundAdvancedViewWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        MainGeneralReportForm mainForm = e.Argument as MainGeneralReportForm;

        if (mainForm!= null && mainForm.InvokeRequired)
        {
            mainForm.BeginInvoke(new ShowViewDelegate(() =>
            {
              advancedSearchView =
                    ObjectFactory.ShowView<IGeneralReportAdvancedSearchView>();                  
              resetEvent.Set();
             }));
            }
        }
    }

If main thread doesn't wait for second thread, the application throws NullReferenceException. Is exist any solution or workaround of this problem?

how to insert textboxes and data from datagridview to tabla sql C#

I have few textboxes and a DataGridView in a winform c#.

enter image description here

I'm trying to make a single insertion but for every foreach iteration my code is inserting data from the datagrid.

enter image description here I want to do this: Insert both textboxes as data from datagrid in a single insertionsql Can anybody help me with this?

.NET Application will run as a Console Application but not as Windows Forms, Debug Works

I have a Windows Application that worked once before on .NET 2.0, and I just wanted to bring it forward to .NET Framework 4. I've done this hundreds of times before without issue.

Long Story Short: After upgrading, I can run the Windows Application (Written in C#) from both Debug and Release Modes. All of My Assemblies are set to build targeting (x86) to make sure that any 32-bit dependencies will run on Windows 7 x64. The strange thing is that when I run the executable from the bin\x86\Debug or Release directories, nothing happens. Literally nothing. The application starts then immediately stops, and there are no error messages, no crashes, no items written to the event log. It just starts and then stops.

The crazy part is if I switch the project output type to "Console Application", then it works to run it from an exe file! (Just have an annoying and ugly console window in the back of the application while it's running).

Has anyone ever heard anything like this before?

Here are the things that I've tried and more information:

  • Looked for any mention of errors in the event log
  • Tried running as Administrator
  • I'm already the computer administrator with Full Access to All directories
  • Tried putting MessageBox.Show statements in Main() function
  • Tried putting Console.WriteLine statements in Main() function
  • Tried making Main functions public.
  • Tried starting the application exe by double clicking it and also running it from the command line (console output didn't appear in that case).
  • Tried executables compiled for Debug AND Release
  • Tried removing the call to start the MainForm.cs, where just the MessageBox code remains.
  • Other Windows Forms applications that are pure .NET 4.0 run fine from their executable.
  • The .NET Framework 4.0 doesn't appear to be corrupted, however, I haven't tried reinstalling it in its entirety.
  • Tried adding a try / catch in the main function to catch and report any errors.
  • Windows 7, 64-bit
  • Visual Studio 2010
  • Windows Updates performed regularly
  • C# for all code

Has anyone seen anything like this? I've been working with C# for over 14 years and haven't seen this behavior before.

Edit: Adding Code from Program.cs minus the namespace tags and using statements

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        try
        {                
            MessageBox.Show("Start");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
            MessageBox.Show("End");
        }
        catch (Exception exp)
        {
            ExceptionDisplay.LaunchUnexpected(exp);
        }
    }
}

The ExceptionDisplay class is just a simple windows form that displays and reports the unexpected error. In this case, it doesn't matter whether the try / catch block is present or not. The same behavior happens with the executable.

EDIT: Adding Exit Codes when in debug mode

The thread 'vshost.RunParkingWindow' (0xf70) has exited with code 0 (0x0).
The thread '<No Name>' (0x25c0) has exited with code 0 (0x0).
The program '[13496] MyProgram.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

EDIT: Adding PropertyGroup items from .csproj file

<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C5FE7F9D-57BB-4A6F-AD53-43BE99BAB6CF}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyNamespace</RootNamespace>
<AssemblyName>MyAssemblyName</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkProfile />
<IsWebBootstrapper>true</IsWebBootstrapper>
<PublishUrl>http://localhost/MyNamespace/</PublishUrl>
<Install>true</Install>
<InstallFrom>Web</InstallFrom>
<UpdateEnabled>true</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>security.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>company.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>

UPDATE: I tried moving all of the files from one project to another new project, and after I got it to compile, the exe file was working. Then, in preparation for deployment, I did a few things to the project (including signing with strong name, changing the program's icon, etc.) and then the exe stopped working. After narrowing it down to the latest sequence of events that I performed, I toggled each item that I changed recently one at a time, and discovered that the item that's causing the exe not to build was setting a non-default icon.

If I switch the default icon to a .ico file, then it will debug but not run the exe. If I switch the icon back to (Default Icon) under Application >> Resources >> Icon and Manifest, then the exe will run just fine outside of the debugger ??? Does anyone have any idea why changing something as innocuous as the program's default icon would make the EXE not run? I will Google / investigate this further after I realized the part that's causing it not to run.

Most Simple way to pragramatically delete textboxes in C#?

I have a dictionary of text boxes I'm using for my program. When changing options I want the boxes to be deleted so that new ones can be made for the next page.

    public static bool command0 () {
        foreach (TextBox tBox in Globals.inputBoxes)
            tBox = null;
        return true;
    }

that returns this error

Cannot convert type 'System.Collections.Generic.KeyValuePair<string,System.Windows.Forms.TextBox>' to 'System.Windows.Forms.TextBox' (CS0030) - C:\Users\e309706\Documents\SharpDevelop Projects\simulator 3\simulator 3\Globals.cs:73,4

Is there a simple and correct way to do what I'm trying to do?

is it possible to change save data from debug folder to actual database

im using a local db on visual studio 2012 for a windows form project.

It works fine but when i want to add a new record during testing, it adds the new record to the debug folder mdf instead of the mdf in the server explorer.

Is there an easy way to stop outputing to that debug folder mdf copy and rather insert the new record into the original database?

Strange behaviour with TextBox not showing string properly

Here is the text assigned to the Text property(pardon the bad quality):

enter image description here

I have copied the text straight from the TextBox on the form, copied it into notepad++ and shown all characters. As you can see everything is well aligned.

Here is how the TextBox looks in the form:

enter image description here

It seems the spacing is now all screwed up. What could be the problem?

Edit: The TextBox is set to true for MultiLine, ReadOnly and WordWrap.

Is it possible to convert a WinForms app into a COM server?

We have a .NET 4.5 WinForms application that would need to be operated through COM by a non .NET app.

Is it possible and if yes, where should I look for achieving this?

What is difference between Control.BeginInvoke() and Dispatcher.BeginInvoke()?

Recently I used Control.BeginInvoke() method to put a method call into queue to be called on UI thread later. I also know there is Dispatcher.BeginInvoke() method. I read some general resources (like this on CodeProject) and still have the question whether behavior of Control.BeginInvoke() is different from Dispatcher.BeginInvoke() or not.

I understand that analogical question can be asked for difference between Control.Invoke() and Dispatcher.Invoke().

VS2012 cannot find newly created forms

VS2012 C#- I have a project that is using Form1.cs as the target form on opening and it provides DB data and editing options. I now have created Form2.cs which will provide reporting based on Form1.cs data. I have added a button on Form1.cs which will link to Form2.cs....However when I type new Form2().Show(); it will not let me perform this action as it cannot find Form2.cs......Seriously confused as other projects DONT have this issue... I can see the form in the solution explorer but cannot link to it. What am I doing wrong?

Edit active WPF control in an active window

I have a WPF window with a WindowsFormsHost object inside it. Ideally, I would like to access the WindowsForm control while the window is active.

I can register a name or anything like that I would need for the WindowsFormsHost control, and then do something along the lines of:

            WindowCollection mainWin = System.Windows.Application.Current.Windows;

In this particular case I know the window I need will always be in mainWin[2], but I'm not sure how I can access the WindowsFormsHost object directly to add a Winform control to it.

Minimum Resolution for WinForms Program

What is the minimum recommended resolution I should design my application to support?

I know there is a wide range of screen sizes available today. I am designing an application, and I have no control over what machine the software will be installed on.

I have a fair amount of information that needs to be relayed, so I would like to maximize what I have without making it too large for some machines.

Windows CE shows noo-existing panel on top of form

I have created simple windows form using .NET 3.5. The application runs of Windows CE device.

When i show this form in my application, there is grey line covering top cca 20 pixels of the form.

Screenshot, in red ellipse:

screenshot

Code:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace eInventorymobile
{
    public partial class frmCustomMessageBox : Form
    {
        #region --- fields ---

        MessageBoxButtons btns;

        #endregion

        #region --- form methods ---

        /// <summary>
        /// Inicializace
        /// </summary>
        /// <param name="btns"></param>
        /// <param name="sTitle"></param>
        /// <param name="sMessage"></param>
        public frmCustomMessageBox(MessageBoxButtons btn, string sTitle, string sMessage)
        {
            InitializeComponent();

            this.btns = btn;
            lblTitle.Text = sTitle;
            lblMessage.Text = sMessage;

        }

        private void frmCustomMessageBox_Load(object sender, EventArgs e)
        {
            switch (this.btns)
            {
                case MessageBoxButtons.OK:
                    btnOk.Visible = true;
                    btnNo.Visible = false;
                    btnYes.Visible = false;
                    btnOk.Focus();
                    break;
                case MessageBoxButtons.YesNo:
                    btnOk.Visible = false;
                    btnNo.Visible = true;
                    btnYes.Visible = true;
                    btnYes.Focus();
                    break;
                default:
                    btnOk.Visible = false;
                    btnNo.Visible = true;
                    btnYes.Visible = true;
                    btnYes.Focus();
                    break;
            }
        }

        #endregion

        #region --- events ---

        /// <summary>
        /// Kliknuti na ANO nastavi dialog result na Yes a ukonci formular
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnYes_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Yes;
            this.Close();
        }

        /// <summary>
        /// Kliknuti na NE nastavi dialog result na Ne a ukonci formular
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNo_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
            this.Close();
        }

        /// <summary>
        /// Kliknuti na OK nastavi dialog result na OK a ukonci formular
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        #endregion

    }
}

namespace eInventorymobile
{
    partial class frmCustomMessageBox
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.MainMenu mainMenu1;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.mainMenu1 = new System.Windows.Forms.MainMenu();
            this.lblMessage = new System.Windows.Forms.Label();
            this.btnYes = new System.Windows.Forms.Button();
            this.btnNo = new System.Windows.Forms.Button();
            this.btnOk = new System.Windows.Forms.Button();
            this.panel1 = new System.Windows.Forms.Panel();
            this.lblTitle = new System.Windows.Forms.Label();
            this.panel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // lblMessage
            // 
            this.lblMessage.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Bold);
            this.lblMessage.ForeColor = System.Drawing.Color.White;
            this.lblMessage.Location = new System.Drawing.Point(12, 44);
            this.lblMessage.Name = "lblMessage";
            this.lblMessage.Size = new System.Drawing.Size(170, 63);
            this.lblMessage.Text = "Message";
            // 
            // btnYes
            // 
            this.btnYes.BackColor = System.Drawing.Color.Gray;
            this.btnYes.Font = new System.Drawing.Font("Tahoma", 10F, System.Drawing.FontStyle.Bold);
            this.btnYes.ForeColor = System.Drawing.Color.White;
            this.btnYes.Location = new System.Drawing.Point(5, 110);
            this.btnYes.Name = "btnYes";
            this.btnYes.Size = new System.Drawing.Size(91, 35);
            this.btnYes.TabIndex = 1;
            this.btnYes.Text = "ANO";
            this.btnYes.Click += new System.EventHandler(this.btnYes_Click);
            // 
            // btnNo
            // 
            this.btnNo.BackColor = System.Drawing.Color.Gray;
            this.btnNo.Font = new System.Drawing.Font("Tahoma", 10F, System.Drawing.FontStyle.Bold);
            this.btnNo.ForeColor = System.Drawing.Color.White;
            this.btnNo.Location = new System.Drawing.Point(103, 110);
            this.btnNo.Name = "btnNo";
            this.btnNo.Size = new System.Drawing.Size(91, 35);
            this.btnNo.TabIndex = 2;
            this.btnNo.Text = "NE";
            this.btnNo.Click += new System.EventHandler(this.btnNo_Click);
            // 
            // btnOk
            // 
            this.btnOk.BackColor = System.Drawing.Color.Gray;
            this.btnOk.Font = new System.Drawing.Font("Tahoma", 10F, System.Drawing.FontStyle.Bold);
            this.btnOk.ForeColor = System.Drawing.Color.White;
            this.btnOk.Location = new System.Drawing.Point(53, 110);
            this.btnOk.Name = "btnOk";
            this.btnOk.Size = new System.Drawing.Size(91, 35);
            this.btnOk.TabIndex = 3;
            this.btnOk.Text = "OK";
            this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
            // 
            // panel1
            // 
            this.panel1.BackColor = System.Drawing.Color.RoyalBlue;
            this.panel1.Controls.Add(this.lblTitle);
            this.panel1.Location = new System.Drawing.Point(0, 0);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(198, 33);
            // 
            // lblTitle
            // 
            this.lblTitle.BackColor = System.Drawing.Color.Transparent;
            this.lblTitle.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold);
            this.lblTitle.ForeColor = System.Drawing.Color.White;
            this.lblTitle.Location = new System.Drawing.Point(5, 7);
            this.lblTitle.Name = "lblTitle";
            this.lblTitle.Size = new System.Drawing.Size(189, 25);
            this.lblTitle.Text = "Title";
            // 
            // frmCustomMessageBox
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            this.AutoScroll = true;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(57)))), ((int)(((byte)(60)))), ((int)(((byte)(69)))));
            this.ClientSize = new System.Drawing.Size(198, 150);
            this.ControlBox = false;
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.lblMessage);
            this.Controls.Add(this.btnOk);
            this.Controls.Add(this.btnNo);
            this.Controls.Add(this.btnYes);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Location = new System.Drawing.Point(20, 60);
            this.MaximizeBox = false;
            this.Menu = this.mainMenu1;
            this.MinimizeBox = false;
            this.Name = "frmCustomMessageBox";
            this.Text = "frmCustomMessageBox";
            this.TopMost = true;
            this.Load += new System.EventHandler(this.frmCustomMessageBox_Load);
            this.panel1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label lblMessage;
        private System.Windows.Forms.Button btnYes;
        private System.Windows.Forms.Button btnNo;
        private System.Windows.Forms.Button btnOk;
        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.Label lblTitle;
    }
}

There is no panel, or label, or texbox, or anything else on the form, where the grey panel is displayed. It is not a control, which should be invisible or anything similar - there is just nothing there. I can not think of anything, which could cause this.

Combobox added to datagridview losses its selection

I am trying to populate a datagrid table and add an additional combobox in a Winforms application to allow the user to select from an exception list.

The datagrid is populated using a Stored Procedure on SQL server. (NOTE: due to my ITs security I have to go through a single server using linked servers to where the data is to query the data so the stored procedure uses dynamic SQL)

The data pulls properly and the additional combobox appears however once I select an exception on 1 row and try to go to the next row, the first combobox's selection disappears.

An additional question, given the nature or how I query the data, how would I update the data on the original sql tables from datagrid? Another stored procedure?

FYI, I'm a SQL developer but I'm fairly new to C#

My code is below for the datagridview method. Thanks in advance.

    public void displayDataGridView(string param)
    {
        SqlConnection con = new SqlConnection("Data Source = SQLServer1; initial catalog=GlbDBNames; integrated security=true ");

        {   
            SqlCommand cmd;
            cmd = new SqlCommand(param, con);
            cmd.CommandTimeout = 60 * 20;
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dg_batchsummary.DataSource = ds.Tables[0];
            dg_batchsummary.Columns[0].Width = 200;
            dg_batchsummary.AutoGenerateColumns = false;
            dg_batchsummary.AllowUserToAddRows = false;


             DataGridViewComboBoxColumn ExceptionList = new DataGridViewComboBoxColumn();
             ExcptionList.HeaderText = "Exception List";
             ExceptionList.Name = "Newexcept";
             ExceptionList.Items.AddRange("Item1","Item2","Item3");

             dg_batchsummary.Columns.Add(ExceptionList);
        }

How form can use in keyUp event of the parent form?

I have a problem,First, I have a parent form ("mainForm") and in this there is a KeyUp event (private void MainForm_KeyUp(object sender, KeyEventArgs e)) Second, I have child form(Frm2) than opened by openDialog command, Now I need that Frm2 can use in MainForm_KeyUp. Really, Frm2 comes to MainForm_KeyUp function, but KeyEventArgs e = Keys.Enter and not all my numbers. A comment: the KeyEventArgs Filling up by magnetic Card reader. This is the code:

private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString());
if (e.KeyData == Keys.Enter)
{
MessageBox.Show("End");
}
}
Wheמ I swip the card in the reader from the mainForm, I get : "12345END", but from the Frm2, I get "END". The KeyEventArgs parameter not have more keys I have to get "12345END" also from frm2.

I'm really thankful for your trial to help!!!
Soh(a programmer embarrassed :( )

Add row from datagridview into datatable

I'm searching over the internet but can't find a solution. I have a specific index of a row from a datagridview. How do I add this row to a datatable? Thank you!

.Net Embedded WebBrowser control is not recognizing tab and arrow key

I have a created a WinForms custom control inheriting from the WebBrowser control. I have put an ActiveX wrapper around that control so we can use in other third party applications.

When the browser control renders a page the tab and arrow keys do not work, i.e., I cannot tab from element to element on the page. If I dock the control in a managed code application it works fine (non-ActiveX mode). But as soon as I drop on a third party app (created using Delphi 7) instantiated as ActiveX control the issue surfaces.

I can install a hook (WH_GETKEYBOARD) and can see the tab keystroke while in the control but have not yet been able to forward the strokes on to the actual browser. I am missing something here but not sure what.

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
[Guid("E82A8888-9999-4444-3333-888888888141")]
[ProgId("MYTEST.BrowserControl")]    
[ClassInterface(ClassInterfaceType.AutoDispatch), ComSourceInterfaces(typeof(ITestComCallableEvents))]
public partial class TestBrowserControl : WebBrowser, ITestComCallableMethods
{
    public TestBrowserControl()
    {
        InitializeComponent();
        //KeyStrokeHook is class implementing low level hooks using windows API
        mksh = new KeyStrokeHook(HookType.WH_KEYBOARD);
        mksh.HookInvoked += new KeyStrokeHook.HookEventHandler(MyHook);
        //install the hook
        mksh.Install();
     }

     void MyHook(object sender, HookEventArgs e)
     {
        IntPtr wParam = e.wParam;
        IntPtr lParam = e.lParam;
        //catch tab key
        if (wParam == (IntPtr)0x09)
        {
           //do something here to forward tab key to browser control
        }
     }
  }

I want to add one folder of javascript in my windows form application setup

I am trying to add one folder of javascript in my windows form application setup

but on doing or releasing setup it is not inlcuding that folder . i saw one option to add manually in the filesystem but JavaScript folder have many files ,If i want to add then i should do it manually .

Please help if there any other option to add those files in Windows form application setup folder

Tags in WinForms TextBox

I want to create a textbox on a WinForms form, where the user cannot input text directly. Instead, the content of the textbox should only be "bubbles" (with a "delete" button), showing a text value.

I'm struggeling to find the correct term for this kind of control/behaviour. It should look a bit like the "Tags"-field on StackOverflow when creating a new question.

Are there any existing controls/settings that allow such behaviour? (I have DevExpress if that helps)

Sorry for the vague question, if i knew better terms for what i'm looking for, i'd probably find something...

Add specific rows from dataGridView depending on search value

Following issue: I have a datatable and a list which contains specific values.

routIds = col1Items.Distinct().ToList();
String searchValue = String.Empty;        
int rowIndex = -1;

for (int i = 0; i < routIds.Count; i++)
{
    searchValue = routIds[i];

    foreach (DataGridViewRow row in form1.dataGridView5.Rows)
    {
        if (row.Cells[form1.routingIdBox.Text].Value != null) // Need to check for null if new row is exposed
        {
            if (row.Cells[form1.routingIdBox.Text].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;

                foreach (DataGridViewColumn column in form1.dataGridView5.Columns)
                    dtRout.Columns.Add(column.Name);

                for (int k = 0; k < form1.dataGridView5.Rows.Count; k++)
                {
                    dtRout.Rows.Add();
                    for (int j = 0; j < form1.dataGridView5.Columns.Count; j++)
                    {
                        datTable.Rows[k][j] = form1.dataGridView5.Rows[rowIndex].Cells[j].Value;
                    }
                }                    
            }
        }
    }
}

I want to search the first column from my datagridview and check if it matches a specific value (from my array - routIds). If yes then I want to add the whole row into a datatable but I don't know how this works exactly. Tried around but I get exceptions (specific row not found).

How can i change the background cell color after the user edited some text

Going from the previous question i had asked that related to color text change after edit. Now it has been requested that i should not highlight the edited text but change the background color.

This is what i want now.

  1. Load existing file with the data to the DataGridView
  2. After loading, DataGridView will populate data
  3. The user will edit text from any cell
  4. After editing the text,
  5. Background color of the edited cell will change color to red,
  6. Only for the edited cell,

How can i change the background color of the edited cell in the DataGridView ?

This is what i tried by changing the background color of the cell.

   private void Gridview_Output_CellBeginEdit_1(object sender, DataGridViewCellCancelEventArgs e)
    {
            DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
            cell.Tag = cell.Value != null ? cell.Value : "";

            if (cell.OwningColumn.Name == "ValueOut")
                cell.Style.BackColor = Color.Yellow;
    }

global

    List<DataGridViewCell> dgvc_List = new List<DataGridViewCell>();

Save button

    private void btnSave_Click(object sender, EventArgs e)
    {
         dgvc_List.Add(cell);
                foreach (DataGridViewCell d in dgvc_List)
                {
                    d.Style.BackColor = Color.White;
                }
                dgvc_List.Clear();
    }

Deserialize and parse only needed arrays from JSON Array

My C# Windows Application uses JavaScriptSerializer to request JSON from certain URL.

JSON looks something like below:

{"outcomes":[{"outcome_coef":2.8,"outcome_id":159370020,"outcome_name":"first","outcome_type_id":4,"outcome_visible":"yes","participant_number":1,"outcome_perc_stat":0.0},
{"outcome_coef":1.19,"outcome_id":159370022,"outcome_name":"second","outcome_type_id":5,"outcome_visible":"yes","participant_number":2,"outcome_perc_stat":0.0},
{"outcome_coef":1.01,"outcome_id":159370021,"outcome_name":"third","outcome_type_id":6,"outcome_visible":"yes","participant_number":3,"outcome_perc_stat":0.0}]}

For example, I only need to get outcome_coef and outcome_id. The rest of the array is not needed.

I am trying to use the following code:

JavaScriptSerializer js = new JavaScriptSerializer();
var response = js.Deserialize<Response>(sr.ReadToEnd());

My Response class looks like this:

public class Response
{
    public Outcomes[] outcomes { get; set; }
}

public class Outcomes
{
    public float outcome_coef { get; set; }
    public int outcome_id { get; set; }
}

But it is not working.

How can I parse only needed part out of JSON without declaring all the array names inside my class?

Setting x & y on ToolTip.Show somehow sets duration as well?

When I call ToolTip.Show() like below;

ToolTip.Show(Message,MyControl);

Everything works perfectly, it shows and goes away when MyControl looses focus. However the position of the ToolTip is over MyControl so I want to add an offset;

ToolTip.Show(Message,MyControl,10,-20);

The ToolTip does position the way I want, it shows when hovering over, but is does not disappear anymore on MyControl loosing focus. The behaviour is similar to setting the duration very high.

When I look at the ToolTip.Show() definition, one of the ways to call it is like this;

public void Show(string text, IWin32Window window, int x, int y);

So how can the ToolTip suddenly stop disappearing when I only add the x & y offset and not touch the duration?

Library to plot histogram on a surface

I need to represent the Image 1 as Image 2.

enter image description here I can create a matrix representing the grey values of Image1 easily but I don't know how to represent this matrix as a 3d surface. Can anyone suggest a library or a way to solve this problem? I'm using WinForms. Thank you

Populate TreeView from DataTable thw right way

I have some trouble managing a treeview the right way. I have a DataGridView and some columns in it. One column shows an ID, the second one a sequence number (one ID can have multiple sequence numbers - for exmple the ID 1000 has the sequence numbers 1,2 and 3). Now I want the user to select certain rows in the datagridview and then fill a treeview the right way. The code:

 foreach (DataGridViewColumn column in form1.dataGridView.Columns)
            datTable.Columns.Add(column.Name);

        for (int i = 0; i < form1.dataGridView.SelectedRows.Count; i++)
        {
            datTable.Rows.Add();
            for (int j = 0; j < form1.dataGridView.Columns.Count; j++)
            {
                datTable.Rows[i][j] =   form1.dataGridView.SelectedRows[i].Cells[j].Value;
            }
        }

        for (int i = 0; i < datTable.Rows.Count;i++ )
        {
            TreeNode node = new TreeNode(datTable.Rows[i][form1.cusIdBox.Text].ToString());

            node.Nodes.Add(datTable.Rows[i][form1.seqNrBox.Text].ToString());
            treeView1.Nodes.Add(node);
        }

This just takes the selected rows and puts them into a datatable. Then each ID gets a node and the sequence number as childnode. What I want to do is:

When I take the example from above - the user selects a row with the ID 1000 where the sequence number is '1'. Now I want to add automatically every other row that has the ID 1000 to my datatable (so three rows with ID 1000 and sequence numbers 1,2 and 3) and then just add a node '1000' with childnodes '1', '2' and '3'. How to do that?

How to check if an usb-driver is installed?

I tried the solution in this thread: How to check whether a driver is installed?

but after I uninstall the driver manually and restart the solution, the driver is still found in the system.

What could be the problem here?

I want to make sure during the installation of my windows-form application, that the driver for the usb device is installed, and if not I want to install it programmatically or give a warning for the user to install it.

any ideas?

thanks in advance :)

populate/execute one lakh records in a faster/better way?

Can we populate/execute 100000 records(currently in for loop customization) in a faster/better way? for(int i=0;i< 100000;i++) {

} Is there any threading (or) any other optimized approach to do this.

Error while retrieving data from OleDb database

I am working on Bank project for which I have written this code for Deposit/Withdrawal Transaction however, I am getting errors as

Error 1 'string' does not contain a definition for 'getDouble' and no extension method 'getDouble' accepting a first argument of type 'string' could be found

Error 2 The name 'result' does not exist in the current context


The Form: http://ift.tt/1GeSJ6O
The Database: http://ift.tt/1IrwCY7

Here is the form code

public partial class DepWithDraw : Form
    {
        OleDbConnection dc = new OleDbConnection();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataTable dt = new DataTable();
        public DepWithDraw()
        {
            InitializeComponent();
            dc.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\ChattBankMDB.mdb";

        }

        private void DepText_Click(object sender, EventArgs e)
        {
            dc.Open();
            OleDbCommand df = new OleDbCommand("Select balance From Accounts Where [acctNO] = ?", dc);
            int updateSet = 0;
            double balance = 0.00;
            double newBalance;
            double depAmount;
            String result;
            newBalance = balance + depAmount;
            string update = "Update Accounts Set Balance = '" + BalDepText.Text + "' Where acctNO = '" + AcctDep.Text + "';";
             balance = result.getDouble("Balance");
            balance = newBalance;
            df.Parameters.AddWithValue("@AcctNo", AcctDep.Text);
            df.Parameters.AddWithValue("@Balance", BalDepText.Text);
            df.ExecuteNonQuery();
            dc.Close();
        }

        private void WithText_Click(object sender, EventArgs e)
        {
            dc.Open();
            OleDbCommand df = new OleDbCommand("Select balance From Accounts Where [acctNO] = ?", dc);
            String update = null;
            int updateSet = 0;
            double balance = 0.00;
            double newBalance;
            double withdrawal;
            balance = result.getDouble("Balance");
            if (balance < withdrawal)
            {
                MessageBox.Show( "Insufficcient Funds");
                throw new Exception();
            }
            else
            {

                /* sets new balance and updates the current database account balance */
                newBalance = balance - withdrawal;
                update = "Update Accounts Set Balance = '" + balWithbtn.Text + "' Where acctNo = '" + AcctWithText.Text + "';";
                df.ExecuteNonQuery();
                this.balance = newBalance;

            }

            df.Parameters.AddWithValue("@AcctNo", AcctWithText.Text);
            df.Parameters.AddWithValue("@Balance", balWithbtn.Text);
        }
    }
}

ToolTip does not show in Status bar addin

I am developing a status bar Add-in for a business program. The add-in returns a usercontrol that is placed on the statusbar by the program. In that User Control I have a small icon in a picturebox. I want to show a tooltip when the user hovers over the icon. I have the following code:

ToolTip Message = new ToolTip();
Message .ShowAlways = true;
Message.SetToolTip(MyIcon);

The Tooltip does not show up however. This is probably due to the StatusStrip.ShowItemToolTips set to false. I cannot change this however since that is part of the program.

Is there any way to force the tooltips to show, or can I inherit a custom class from the ToolTip class and have it show up? I do not want to create a complete new class for something that is already there.

Does a custom control inherit base class INotifyPropertyChanged interface?

I have a base generic custom control (grandparent). In order for the designer to display inheriting controls without problem, I first inherit (parent) from grandparent, and finally I inherit from parent. The child control is the control using on the forms.

If I implement the INotifyPropertyChanged interface in the grandparent control, will the child be recognized as implementing this interface?

Refresh Paint after Scroll is Completed

I have a datagridview which places a black border around selected cell(s). My code works fine, up until I scroll while making my selection. My top border disappears when I scroll down while making a selection, which is not a problem at this point, because it shows that there are more selected cells out of view, the problem I have is once I've made my selection and then return to the top, the top border never returns. I've noticed that on enter to a cell, the dgv repaints, and this I assume is the reason why my top border is not painting, because it is out of view and once I scroll back to the top, I'm not entering any new cells, so the top border never repaints.

So I added a scroll event to refresh my dgv paint, but this seems to repaint then scroll and not scroll the repaint, which results in even further selected cell borders not displayed.

So my question is, is there a way to trigger the repaint after the scroll is complete?

Below is my code, not sure if it is relevant to show, but here it is.

    Private Sub dgvdefault_paint(sender As Object, e As PaintEventArgs)
    With dgvdefault

        ' draw border around dgv
        e.Graphics.DrawRectangle(penborder, 0, 0, .Width - 1, .Height - 1)


        For Each cell In .SelectedCells

            ' get cell position and size

            a = cell.rowindex
            b = cell.columnindex

            Dim myrect As Rectangle = (.GetCellDisplayRectangle(b, a, False))
            Dim dgvdefault_headerrectangle As Rectangle = (.GetCellDisplayRectangle(-1, -1, False))

            ' top border

            If a = 0 Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1, myrect.Y - 1, myrect.X - 1 + myrect.Width, myrect.Y - 1)
            ElseIf .Rows(a - 1).Cells(b).Selected = False Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1, myrect.Y - 1, myrect.X - 1 + myrect.Width, myrect.Y - 1)
            End If

            ' bottom border

            If a = .RowCount - 1 Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1, myrect.Y - 1 + myrect.Height, myrect.X - 1 + myrect.Width, myrect.Y - 1 + myrect.Height)
            ElseIf .Rows(a + 1).Cells(b).Selected = False Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1, myrect.Y - 1 + myrect.Height, myrect.X - 1 + myrect.Width, myrect.Y - 1 + myrect.Height)
            End If

            ' left border

            If b = 0 Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1, myrect.Y - 1, myrect.X - 1, myrect.Y - 1 + myrect.Height)
            ElseIf .Rows(a).Cells(b - 1).Selected = False Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1, myrect.Y - 1, myrect.X - 1, myrect.Y - 1 + myrect.Height)
            End If

            ' right border

            If b = .ColumnCount - 1 Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1 + myrect.Width, myrect.Y - 1, myrect.X - 1 + myrect.Width, myrect.Y - 1 + myrect.Height)
            ElseIf .Rows(a).Cells(b + 1).Selected = False Then
                e.Graphics.DrawLine(Pens.Black, myrect.X - 1 + myrect.Width, myrect.Y - 1, myrect.X - 1 + myrect.Width, myrect.Y - 1 + myrect.Height)
            End If

        Next

    End With

End Sub

Private Sub dgvdefault_scroll(sender As Object, e As ScrollEventArgs)

    dgvdefault.Refresh()

End Sub

New column is added automaticlly when filling datagridview

I'm using linq to filling my datagrid view with this method:

public List<HopDongCungCap> XemHopDong()
        {
            return QL.HopDongCungCaps.ToList();
        }

and this is my result: http://ift.tt/1E5vR7s

My dbo.HopDongCungCap just has 1-4 column but i dont know why it appears the 5th column

Note that dbo.NhaCungCap has a relationship with dbo.HopDongCungCap

Thank you for watching my question!

How to Print DataGridView Rows to Reports in windows Forms C#. [on hold]

Hello Everyone i would like to Print DataGridView Visible Rows to Microsoft Reports View. I will appreciate feedback.

Thank You

C# update then delete record in datagridview

In my project I need to update the attn_dateTimeOut in database. After I updated it will automatic delete the specific row record that had been updated. I had two question:

1) In my database there are a few table is assign not null."attn_dateTimeOut" is a table that haven insert any record. When I update it using below code,it work and can update but it comes out error. Error show "record cannot be null".

2) I want to make it when I updated the "attn_dateTimeOut", it will auto delete the row of updated record. I do using back code "DeleteRecord" but it nothing change! How should I do?

Here is my code:

private void txt_proximity_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        TMPB_attn row_TMPN_attn = BusinessLogicLayer.TMS_GET_PROXIMITY_VALID_TO_USE(txt_proximity.Text);
        if (!String.IsNullOrEmpty(txt_proximity.Text))
        {
            using (TMPB_attn_DAL dalObj = new TMPB_attn_DAL())
            {
                if (row_TMPN_attn != null)
                {
                    try
                    {
                        row_TMPN_attn.attn_dateTimeOut = Convert.ToDateTime(DateTime.Now);
                        dalObj.UpdateRecord(row_TMPN_attn);
                        dalObj.DeleteRecord();
                        MessageBox.Show("Update Successful");
                        txt_proximity.Text = "";
                        loadGridView();
                    }
                    catch (Exception es)
                    {
                        MessageBox.Show(es.Message);
                    }
                }
                else
                {
                    MessageBox.Show("Proximity No. is not exist");
                    txt_proximity.Text = "";
                }
            }
        }
        else
        {
            MessageBox.Show("Please try again");
            txt_proximity.Text = "";
        }
    }
}

Get the value of a scrollbar's scroll for a Winforms Text Box (C#)

I am creating a Windows Form Application using C#

I require a checkbox to be greyed out until the user scrolls to the bottom of a text box.

How can I get the value of the textbox's scrollbar position?

method completes but data is not inserted into SQL database

i have a method which should save user details to a local database on Visual Studio, the method below is in question

   private void btnSaveDetails_Click(object sender, EventArgs e)
    {
        //var IssueDate = this.dtpIssueDate.Value.ToString("yyyy-MM-dd HH:mm:ss") + "')";
        //var ExipryDate =this.dtpExpiryDate.Value.ToString("yyyy-MM-dd HH:mm:ss") + "')";
        var mainMenu = new frmMainMenu();
        SqlConnection sc = new SqlConnection();
        SqlCommand com = new SqlCommand();
        sc.ConnectionString = (Properties.Settings.Default.BioEngineering);
        sc.Open();
        com.Connection = sc;


        com.Parameters.AddWithValue("@Forename", this.txtFirstName.Text);
        com.Parameters.AddWithValue("@Surname", this.txtLastName.Text);
        com.Parameters.AddWithValue("@Company", this.txtCompany.Text);
        com.Parameters.AddWithValue("@SecurityLevel", this.cboSecurityLevel.Text);
        com.Parameters.AddWithValue("@IssueDate", this.dtpIssueDate.Value);
        com.Parameters.AddWithValue("@ExpiryDate", this.dtpExpiryDate.Value);
        com.Parameters.AddWithValue("@CardID", this.cboCardID.Text);

        com.CommandText = "INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES (@Forename,@Surname,@Company,@SecurityLevel,@IssueDate,@ExpiryDate,@CardID)";
        com.ExecuteNonQuery();
        sc.Close();
        this.Hide();
        mainMenu.Show();
    }

I get no errors and when i add a breakpoint at com.ExecuteNonQuery it appears to have the correct data....any ideas? i first thought it was the connection string but seen other sites with similar formats so dont think its it

Copy a rectangluar portion of Bitmap using LockBits

I'm using the following code to lock a rectangle region of a bitmap

    Recangle rect = new rect(X,Y,width,height);
    BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly,
                            bitmap.PixelFormat);

What seems to be the issue is bitmapData.Scan0 gives me IntPtr of the top left corner of the rectangle. When I use memcpy, it copies the contiguous region in memory upto the specified length.

memcpy(bitmapdest.Scan0, bitmapData.Scan0, 
             new UIntPtr((uint (rect.Width*rect.Height*3)));

If following is my bitmap data,

a b c d e
f g h i j
k l m n o
p q r s t

and if the rectangle is (2, 1, 3 ,3) i.e, the region

g h i
l m n
q r s

using memcpy gives me bitmap with the following region

g h i
j k l
m n o

I can understand why it copies the contiguous memory region. Bottom line is I want to copy a rectangle region using Lockbits.

Edit: I used Bitmap.Clone, but it was faster when I flipped the Y (less than 500ms)

bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

but it was very slow when I didn't flip Y (30 seconds)

Image size used was 60000x1500.

Change Font.Size in a RichTextBox .SelectionFont with multiple FontFamily

How can I change the Font.Size in a RichTextBox .SelectionFont (wich has two or three different FontFamily), without affecting the FontFamilyand the FontStyle

This one works fine, if i have only one Font.Family

richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, 12);

But, if I have more, it throwing nullexception.

Thx

How to display list media like windows in winforms?

How to display media list like windows in winforms ?

Like this:

enter image description here

How to count record using 2 conditions in crystal report

I have a table in crystal report with rows and columns, for each intersection of row (Projects) and column (Employees), I want to put a count of records using 2 conditions (value of row and value of column) I tried: if ({table.NameEmployee} = "Mark" and {table.ProjectName} = "Project1") then count ({table.idEmployee}) and the same thing for the other intersection with different value of row and column but it doesn't work !!

Function doesn't return value from another thread

I'm working with multithreading and faced with one strange moment. I have following code:

var advancedSearchView = ObjectFactory.ShowView<IGeneralReportAdvancedSearchView>()

In this case code works fine. But when I try to use BackgroundWorker fuction ShowView doesn't return any value.

BackgroundWorker backgroundWorker = new BackgroundWorker();

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
   var simpleView= ObjectFactory.ShowView<IGeneralReportSimpleView>();
}

string ShowView<T>()
{
return typeof(T).Name;
}

My backgroung worker calling from the same method as advancedSearchView

backgroundWorker.RunWorkerAsync();

Could you be so kind to advise how to solve current problem?

How to use onPaint on Custom Combobox?

Due to some constrains, I am in a position to create custom-combobox with which add a dot at right to it (while it load to the form). This can be label with filled color.

I try to use OnPaint event, it is not help me to achieve it.

Protected Overrides Sub OnPaint(e As PaintEventArgs)
    MyBase.OnPaint(e)

    ' Create Label as per specification

    ' Add label to the parent of the combo-box
    Me.Parent.Controls.Add(lableControl)
End Sub

I may miss something here.. It may be very simple. But it swallows my time. I appreciate, suppose you have any other idea to achieve this. Thank you.

Custom group box not binding to bindingsource

I need to bind a GroupBox to a BindingSource, which in turn is bound to the following object:

public class CustomerType
{
    public int Id {get; set;}
    public string Name {get; set;}
    public MemberType MemberType {get; set;}
}

public enum MemberType {Adult, Child}

I followed this answer to create a custom GroupBox. I also set the data bindings as follows:

groupBoxMemberType.DataBindings.Add("Selected", this.bindingSource, "MemberType");

However, when loading an existing object, I get the following exception:

DataBinding cannot find a row in the list that is suitable for all bindings.

The exception occurs when setting the data source:

customerType = customerTypeRequest.Load(id);
bindingSource.DataSource = customerType;  //raises exception

What am I missing? Is there an alternative to get radio buttons to bind to a datasource, specifically a BindingSource?

lundi 20 avril 2015

How can i read all the lines from a text file in specific places and use the data?

string[] lines = File.ReadAllLines(@"c:\wmiclasses\wmiclasses1.txt");
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].StartsWith("ComboBox"))
                {

                }
            }

And this is how the text file content look like:

ComboBox Name cmbxOption

Classes Win32_1394Controller
Classes Win32_1394ControllerDevice

ComboBox Name cmbxStorage

Classes Win32_LogicalFileSecuritySetting
Classes Win32_TapeDrive

What i need to do is some things:

  1. Each time the line start with ComboBox then to get only the ComboBox name from the line for example cmbxOption.

    Since i have already this ComboBoxes in my form1 designer i need to identify where the cmbxOption start and end and when the next ComboBox start cmbxStorage.

  2. To get all the lines of the current ComboBox for example this lines belong to cmbxOption:

Classes Win32_1394Controller Classes Win32_1394ControllerDevice

  1. To create from each line a Key and Value for example from the line:

Classes Win32_1394Controller

Then the key will be Win32_1394Controller and the value will be only 1394Controller

Then the second line key Win32_1394ControllerDevice and value only 1394ControllerDevice

  1. To add to the correct belonging ComboBox only the value 1394Controller.

  2. To make that when i select in the ComboBox for example in cmbxOption the item 1394Controller it will act like i selected Win32_1394Controller.

For example in this event:

private void cmbxOption_SelectedIndexChanged(object sender, EventArgs e)
        {
            InsertInfo(cmbxOption.SelectedItem.ToString(), ref lstDisplayHardware, chkHardware.Checked);

        }

In need that the SelectedItem will be Win32_1394Controller but the user will see in the cmbxOption only 1394Controller without the Win32_

This is the start of the method InsertInfo

private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
        {

That's why i need that the Key will be Win32_1394Controller but i want that the user will see in the ComboBox only 1394Controller without the Win32_

Specified cast is not valid error in Datagridview c#

This is a really weird error I've never had before. I have added a checkbox to my datagridview like this:

DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
datagrid.Columns.Insert(0, checkBoxColumn);

I get the error

Specified cast is not valid

And it highlights this in cell formating of the datagrid:

for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{
    if ((int)datagrid.Rows[e.RowIndex].Cells[7].Value <= 5)
    {
        this.datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
    }

This checks if a value in cell 7 is below the value or equal to 5 and if it is changes it to red. I have tried changing the cell to 8 because I thought it had moved since I've added a new column at 0 however it didn't work.

Mouse pointer position when pointer is not on winform

I'm able to get the mouse position when it is within the form. Here is my code-

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    lblXPosition.Text = MousePosition.X.ToString();
    lblYPosition.Text = MousePosition.Y.ToString();
}

But it does not work when the pointer is outside the form. Any suggestion?

Loading form before while loop in game

I am developing a game in C# .But it has some infinite loop that prevents form from being loaded. I have tried many solutions available on internet, But that doesn't seems to work.

My problem is :"How to load the form before execution of while loop."?

My Program.cs Source

namespace SumSwamp
{
static class Program
{

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var window = new Form1();
        window.Show();

    }
}
}

Form1.cs :

namespace SumSwamp
{
public partial class Form1 : Form
{
    public static int DieLargeNum = 0;
    public static int DieSmallNum = 0;
    public static int DieOperator = 0;
    public static int DieTotal = 0;
    public static int TotalSpaces = 42;
    public static int CompSum = 0;
    public static int PlayerSum = 0;
    public static Boolean PlayersRoll = true;
    public static Boolean WaitForRoll = true;
    public static int Turn = 0;

    public Form1()
    {
        InitializeComponent();
        this.Load += new EventHandler(this.Form1_Load);
        while(Turn == 0) //INFINITE LOOP
        {
            if (WaitForRoll==false)
            {
                DieTotal=DieLargeNum;
                Random rnd1 = new Random();
                DieLargeNum = rnd1.Next(1, 7);
                if (DieTotal>DieLargeNum)
                {
                    Turn = 1;
                    labelStatus.Text = "Player 1's Turn";
                    WaitForRoll=true;
                }
                else
                {
                    Turn = 2;
                    labelStatus.Text = "Player 2's Turn";
                    WaitForRoll = false;
                }
            }
        }

        while ((CompSum < TotalSpaces) & (PlayerSum < TotalSpaces))//INFINITE LOOP
        {
            while (Turn == 1)
            {
                if (WaitForRoll == false)
                {
                    if (DieOperator == 1)
                    {
                        DieTotal = DieLargeNum + DieSmallNum;
                    }
                    else
                    {
                        if (DieLargeNum > DieSmallNum)
                        {
                            DieTotal = DieLargeNum - DieSmallNum;
                        }
                        else
                        {
                            DieTotal = DieSmallNum - DieLargeNum;
                        }

                    }
                    PlayerSum = PlayerSum + DieTotal;
                    Turn = 2;
                    PlayersRoll = false;
                    labelStatus.Text = "Player 2's Turn";
                }
            }

            while (Turn == 2)
            {
                Random rnd1 = new Random();
                DieLargeNum = rnd1.Next(1, 7);
                Random rnd2 = new Random();
                DieSmallNum = rnd2.Next(1, 7);
                Random rnd3 = new Random();
                DieOperator = rnd3.Next(1, 3);
                labelDieLargeNum.Text = DieLargeNum.ToString();
                labelDieSmallNum.Text = DieSmallNum.ToString();
                if (DieOperator == 1)
                {
                    labelDieOperator.Text = "+";
                }
                else
                {
                    labelDieOperator.Text = "-";

                }

                if (DieOperator == 1)
                {
                    DieTotal = DieLargeNum + DieSmallNum;
                }
                else
                {
                    if (DieLargeNum > DieSmallNum)
                    {
                        DieTotal = DieLargeNum - DieSmallNum;
                    }
                    else
                    {
                        DieTotal = DieSmallNum - DieLargeNum;
                    }
                }
                CompSum = CompSum + DieTotal; 
                Turn = 1;
                PlayersRoll = true;
                labelStatus.Text = "Player 1's Turn";                    
            }

        }
        if (CompSum>=TotalSpaces)
        {
            labelResult.Text = "CPU Player has won!";
        }
        else
        {
            labelResult.Text = "You win!";
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void buttonRoll_Click(object sender, EventArgs e)
    {
        if (PlayersRoll == true)
        {
            Random rnd1 = new Random();
            DieLargeNum = rnd1.Next(1, 7);
            Random rnd2 = new Random();
            DieSmallNum = rnd2.Next(1, 7);
            Random rnd3 = new Random();
            DieOperator = rnd3.Next(1, 3);
            WaitForRoll = false;
            labelDieLargeNum.Text = DieLargeNum.ToString();
            labelDieSmallNum.Text = DieSmallNum.ToString();
            if(DieOperator == 1)
            {
                labelDieOperator.Text = "+";
            }
            else
            {
                labelDieOperator.Text = "-";

            }

        }
    }

}
}