none
Message box isn't appeared RRS feed

  • Question

  • When I enter correct user and password, then I have message "connection succeeded", but when I enter wrong password or user -  messagebox isn't appeared. How to write code messagebox with message "password or user is incorrect" would be appeared?

     var ConnectionString = $"Server={serverName};" + $"Database={databaseName};" + $"User={userName};" + $"Password={userPassword};";
                using (var cn = new SqlConnection { ConnectionString = ConnectionString })
                {
                    try
                    {
                        cn.Open();
                        if (cn.State == ConnectionState.Open)
                        {
                            MessageBox.Show("Connection succeeded");
                        }
                        else
                        {
                            MessageBox.Show("Password or User is incorrect");
                        }
                        return true;
                    }
                        
                    catch (Exception e)
                    {
                        return false;
                    }
                    cn.Close();
                }    

    Wednesday, November 6, 2019 10:15 AM

Answers

  • Did you already try to put one more MessageBox inside the catch block?

    • Marked as answer by Decompressor Thursday, November 7, 2019 7:37 AM
    Wednesday, November 6, 2019 3:34 PM
  • Hi pavlob,

    Thank you for posting here.

    For your question, you want to show MessageBox when the user enters the wrong password.

    But in your code, if the password is wrong, an exception is caught when the connection is opened, so the else code block will not execute anyway.

    You should put the MessageBox in the catch block.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Decompressor Thursday, November 7, 2019 6:43 AM
    Thursday, November 7, 2019 6:19 AM

All replies

  • Hello,

    I recommend using Credential property of the Connection object as shown below.

    using System;
    using System.Data.SqlClient;
    using System.Security;
    
    namespace MinimalApproachExample
    {
        public class DatabaseUser
        {
            private string serverName;
            private string catalogName;
            public DatabaseUser(string pServerName, string pCatalogName)
            {
                serverName = pServerName;
                catalogName = pCatalogName;
            }
            public bool SqlCredentialLogin(string pUserName, string pPassword)
            {
    
                string connectionString = $"Data Source={serverName};" +
                                          $"Initial Catalog={catalogName};";
    
    
                var securePassword = new SecureString();
    
                foreach (var character in pPassword)
                {
                    securePassword.AppendChar(character);
                }
    
                securePassword.MakeReadOnly();
    
                var credentials = new SqlCredential(pUserName, securePassword);
    
                using (var cn = new SqlConnection { ConnectionString = connectionString })
                {
                    try
                    {
                        cn.Credential = credentials;
                        cn.Open();
                        return true;
    
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }
        }
    }
    

    In a form with two TextBox controls to accept user name and password

    using System;
    using System.Windows.Forms;
    
    namespace MinimalApproachExample
    {
    	public partial class LoginForm
    	{
    		public LoginForm()
    		{
    			InitializeComponent();
    		}
    		private void ShowHidePasswordCheckBox_CheckedChanged(object sender, EventArgs e)
            {
                PasswordTextBox.PasswordChar = ShowHidePasswordCheckBox.Checked ? '*' : '\0';
            }
    		private void LoginButton_Click(object sender, EventArgs e)
    		{
    
    			if (!string.IsNullOrWhiteSpace(UserNameTextBox.Text) && !string.IsNullOrWhiteSpace(PasswordTextBox.Text))
    			{
    
    				var ops = new DatabaseUser(Environment.UserName == "Karens" ? "KARENS-PC" : ".\\SQLEXPRESS", "UserLoginExample"); 
    
                    // perform login
                    var loginResults = ops.SqlCredentialLogin(UserNameTextBox.Text, PasswordTextBox.Text);
    
                    if (loginResults)
                    {
    
                        var successValue = ops.DoWork(UserNameTextBox.Text, PasswordTextBox.Text);
                        var workResult = string.IsNullOrWhiteSpace(successValue);
    
                        if (workResult)
                        {
                            // operation was successful
                            MessageBox.Show("Work complete");
                        }
                        else
                        {
                            // operation has failed
                            MessageBox.Show(successValue);
                        }
                    }
                    else
                    {
                        // login failed for one or more reasons
                        MessageBox.Show("Login failed");
                    }
    			}
    			else
    			{
                    // missing user name and or user password
    				MessageBox.Show("Incomplete information to continue.");
    			}
    		}
    		private void CancelButton_Click(object sender, EventArgs e)
    		{
    			Close();
    		}
    	}
    }

    In addition to the above, you can do a specific assertion on a failed login in a catch as per below which can also be seen in full in the following GitHub page which is in a class where user name and password is encrypted from a login form.

    catch (SqlException failedLoginException) when (failedLoginException.Number == 18456)


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, November 6, 2019 10:43 AM
    Moderator
  • "Karens" ? "KARENS-PC" : ".\\SQLEXPRESS", "UserLoginExample"

    What is it?

    Wednesday, November 6, 2019 3:14 PM
  • Did you already try to put one more MessageBox inside the catch block?

    • Marked as answer by Decompressor Thursday, November 7, 2019 7:37 AM
    Wednesday, November 6, 2019 3:34 PM
  •  "Karens" ? "KARENS-PC" : ".\\SQLEXPRESS", "UserLoginExample"); 
    
    What is it?
    Wednesday, November 6, 2019 3:58 PM
  • "Karens" ? "KARENS-PC" : ".\\SQLEXPRESS", "UserLoginExample"

    What is it?

    KARENS-PC is the SQL-Server name, for example for SQL-Express it would be .\SQLEXPRESS, I'm using KARENS-PC as I use a Enterprise version for SQL-Server.

    UserLoginExample is the database residing on either KARENS-PC or .\SQLEXPRESS.

    Viewed from SSMS.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, November 6, 2019 4:03 PM
    Moderator
  • Hi pavlob,

    Thank you for posting here.

    For your question, you want to show MessageBox when the user enters the wrong password.

    But in your code, if the password is wrong, an exception is caught when the connection is opened, so the else code block will not execute anyway.

    You should put the MessageBox in the catch block.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Decompressor Thursday, November 7, 2019 6:43 AM
    Thursday, November 7, 2019 6:19 AM
  • '*' : '\0';

    What is it?

    Thursday, November 7, 2019 7:59 AM