The code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace LaboratoryGroupings
{
public partial class CRUD : Form
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ConnectionString);
char action;
public CRUD()
{
InitializeComponent();
}
private void CRUD_Load(object sender, EventArgs e)
{
LoadData();
buttonSetup("enable");
}
public void LoadData()
{
con.Open();
using (con)
{
SqlDataAdapter sda = new SqlDataAdapter("Select * from tbl_User", con);
DataTable dt = new DataTable();
sda.Fill(dt);
DGUserData.DataSource = dt;
}
con.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd;
switch (action)
{
case 'a':
cmd = new SqlCommand("INSERT INTO tbl_User (userName, userPass) Values (@username, @userpass)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@username", txtUN.Text.Trim());
cmd.Parameters.AddWithValue("@userpass", txtPW.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Added new User Successfully!", "User Maintenance", MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
case 'u':
break;
case 'd':
break;
}
con.Close();
LoadData();
}
}
}
In the startup of the form it works fine without the error, but when I input and save the data this error shows up for the con.open();
:
System.InvalidOperationException: 'The ConnectionString property has not been initialized.'
I tried to initialize the connectionString
inside the case, but the con.Open()
in the LoadData()
method shows the same error this time even though it starts up just fine without the error.
This is the content of my App.config
, I already added the connectionString inside:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<connectionStrings>
<add name="dbConnect" connectionString="data source=DESKTOP-UT4DEFE\MSSQLSERVER01; initial catalog=LabDB;
integrated security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>