how to fix Sql connection and Sql command being underlined red in Visual Studio?

Codified_ 0 Reputation points
2024-01-25T05:32:34.65+00:00

Hello,
So i recently began to code a registration application to store the data of students using both Visual Studio and SQL Server but the namespace of SqlConnection and SqlCommand have been underlined by read by Visual Studio. I checked the Sql server connection and verified everything I am aware of what could be causing the error. I also made sure it was properly case sensitive aswell. Yet its not resolved, I cannot move forward with the project as it remains to be underlined. Could someone please tell me on what I could do resolve this issue.

Thank you.
The Code is given below,

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace StudentRegistrationForm
{
    public partial class RegistrationForm : Form
    {
        // Connection string for the SQL Server database
        private string connectionString = "Data Source=MYPC;Initial Catalog=Student;Integrated Security=True;Trust Server Certificate=True";

        public RegistrationForm()
        {
            InitializeComponent();

            // Populate the Registration Number ComboBox with placeholder values
            // Users can choose their own Registration Number
            cmbRegistrationNumber.Items.AddRange(new object[] { "101", "102", "103", "104" });
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            // Check if all fields are filled
            if (AllFieldsFilled())
            {
                // Get values from the form
                string registrationNumber = cmbRegistrationNumber.Text;
                string firstName = txtFirstName.Text;
                string lastName = txtLastName.Text;
                DateTime dateOfBirth = dtpDateOfBirth.Value;
                string gender = (rbMale.Checked) ? "Male" : "Female";
                string address = txtAddress.Text;
                string email = txtEmail.Text;
                string mobileNumber = txtMobileNo.Text;
                string landlineNumber = txtLandlineNo.Text;
                string parentsName = txtParentsName.Text;
                string nic = txtNIC.Text;
                string contactNumber = txtContactNo.Text;

                // Insert data into the database
                if (InsertIntoDatabase(registrationNumber, firstName, lastName, dateOfBirth, gender, address, email,
                                        mobileNumber, landlineNumber, parentsName, nic, contactNumber))
                {
                    MessageBox.Show("Record Added Successfully", "Register Student", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // Clear the form for the next registration
                    ClearForm();
                }
                else
                {
                    MessageBox.Show("Failed to add record to the database", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Please fill in all fields to register.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // Check if all fields are filled
        private bool AllFieldsFilled()
        {
            // You can add additional validation if needed
            return !string.IsNullOrWhiteSpace(cmbRegistrationNumber.Text) &&
                   !string.IsNullOrWhiteSpace(txtFirstName.Text) &&
                   !string.IsNullOrWhiteSpace(txtLastName.Text) &&
                   !string.IsNullOrWhiteSpace(txtAddress.Text) &&
                   !string.IsNullOrWhiteSpace(txtEmail.Text) &&
                   !string.IsNullOrWhiteSpace(txtMobileNo.Text) &&
                   !string.IsNullOrWhiteSpace(txtLandlineNo.Text) &&
                   !string.IsNullOrWhiteSpace(txtParentsName.Text) &&
                   !string.IsNullOrWhiteSpace(txtNIC.Text) &&
                   !string.IsNullOrWhiteSpace(txtContactNo.Text) &&
                   (rbMale.Checked || rbFemale.Checked);
        }

        // Insert data into the database
        private bool InsertIntoDatabase(string registrationNumber, string firstName, string lastName, DateTime dateOfBirth,
                                       string gender, string address, string email, string mobileNumber,
                                       string landlineNumber, string parentsName, string nic, string contactNumber)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    // Assuming you have a table named 'Registration' with appropriate columns
                    string query = "INSERT INTO Registration (RegistrationNumber, FirstName, LastName, DateOfBirth, Gender, Address, Email, " +
                                   "MobileNumber, LandlineNumber, ParentsName, NIC, ContactNumber) " +
                                   "VALUES (@RegistrationNumber, @FirstName, @LastName, @DateOfBirth, @Gender, @Address, @Email, " +
                                   "@MobileNumber, @LandlineNumber, @ParentsName, @NIC, @ContactNumber)";

                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        // Add parameters to the query
                        command.Parameters.AddWithValue("@RegistrationNumber", registrationNumber);
                        command.Parameters.AddWithValue("@FirstName", firstName);
                        command.Parameters.AddWithValue("@LastName", lastName);
                        command.Parameters.AddWithValue("@DateOfBirth", dateOfBirth);
                        command.Parameters.AddWithValue("@Gender", gender);
                        command.Parameters.AddWithValue("@Address", address);
                        command.Parameters.AddWithValue("@Email", email);
                        command.Parameters.AddWithValue("@MobileNumber", mobileNumber);
                        command.Parameters.AddWithValue("@LandlineNumber", landlineNumber);
                        command.Parameters.AddWithValue("@ParentsName", parentsName);
                        command.Parameters.AddWithValue("@NIC", nic);
                        command.Parameters.AddWithValue("@ContactNumber", contactNumber);

                        // Execute the query
                        command.ExecuteNonQuery();
                    }

                    return true;
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions here
                MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        // Clear all fields in the form
        private void ClearForm()
        {
            cmbRegistrationNumber.Text = "";
            txtFirstName.Text = "";
            txtLastName.Text = "";
            dtpDateOfBirth.Value = DateTime.Now;
            rbMale.Checked = false;
            rbFemale.Checked = false;
            txtAddress.Text = "";
            txtEmail.Text = "";
            txtMobileNo.Text = "";
            txtLandlineNo.Text = "";
            txtParentsName.Text = "";
            txtNIC.Text = "";
            txtContactNo.Text = "";
        }
    }
}

Developer technologies .NET Other
SQL Server Other
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2024-01-25T07:20:31.9566667+00:00

    Hi @Codified_ , Welcome to Microsoft Q&A,

    Your project may enter some unknown mistakes.

    You can try some possible suggestions:

    If you try to create a new program, can you complete the SQL connection? Close and reopen Visual Studio. This helps refresh the Intellisense cache and resolves temporary failures.

    Sometimes, the Intellisense of Visual Studio may have problems. Try to clean up and rebuild projects. Right -click the project in the "Solution Resource Manager", select "Clean", and then right -click and select "Re -generating".

    If you still encounter a problem, you can try to install the package through the Nuget package manager console. Open the console ("Tools"> "Nuget Bag Manager"> "Bag Manager Console") and run the following command: System.data.SQLClient

    If it is the first time you use VS, there is this problem. In the end, you can try to go to Repair in Installer and check whether the VS compiler is installed with SQL.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".   Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. RATAN SEN CHAUDHARY 0 Reputation points
    2024-01-25T10:21:36.32+00:00

    Hi @Codified_ , Welcome to Microsoft coding world.

    Just make sure that in project reference System.Data is added or not.
    In case if not, please follow the below steps and rebuild your project, error will go.

    1. Right click on Reference
    2. Click -> Add reference
    3. Select Assemblies
    4. Search for System.Data
    5. Select it and press Ok button.
    6. Finally rebuild your project. User's image

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.