1

I designed a C# desktop app in visual studio 2019 and for database used sql server express 2019 edition. i am trying to run this app on another pc. i have installed sql server express 2019 in the other pc also MS server management studio 2019 installed and restored the database. everything works fine like login,saving updating,deleting but when i try to fetch data to datagridview it shows "system.data.sqlclient.sqlexception - a network related or instance specific error occurred while establishing a connection to sql server. the server was not found or was not accessible. verify instance name is correct and sql server is configured to allow remote connections.(provider: sql network interfaces, error: 26 - error locating server/instance specified)."

all the ports are enabled and firewall rule is also enabled in the client pc.

i am using the below connection string for the connection.

class Connection
  {
       SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=icon;Integrated Security=True");

    public SqlConnection active()
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        return con;
    }
}

Please help anyone as i am not able to get what is the problem going on.

Belowcode is working

 private void loginBtn_Click(object sender, EventArgs e)
     {
        Connection con = new Connection();
        SqlCommand cmd = new SqlCommand("select * from [user] where 
        Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text 
        + "'", con.active());
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            MessageBox.Show("Login Successful", "Sucsess", 
              MessageBoxButtons.OK, MessageBoxIcon.Information);
            new dashboard().Show();
            this.Hide();
        }

but this is not working.it shows the error when i try to fetch the data.

public partial class AllSudent : Form
{
    public AllSudent()
    {
        InitializeComponent();
    }

    Connection con = new Connection();
    public int studentID;
    private void AllSudent_Load(object sender, EventArgs e)
    {
       
        GetStudentsRecord();
    }

    public void GetStudentsRecord()
    {
        SqlCommand cmd = new SqlCommand("Select * From [student]", 
        con.active());
        DataTable dt = new DataTable();
        SqlDataReader sdr = cmd.ExecuteReader();
        dt.Load(sdr);

        sdataGridView.DataSource = dt;
    }

dataset for datagridAll files of the app

  • 1
    so your claim is that that method is used to get e.g. a connection when doing a login and it works fine to select data out of the users table, but then the exact same method when used to fetch data for some grid, it fails? Post the working and the failing code – Caius Jard Feb 08 '21 at 10:54
  • 1
    Incidentally, it doesn't look like a good pattern you're using here - the way things are structured you could end up holding a connection open for longer than necessary, exhausting the pool ,or having one class close a connection another class is still using. You should create new connections on demand, in a `using` and ensure they close when done, otherwise you're defeating all the connection management (pooling) that is built into the framework, that is expecting connections to be used in a particular way – Caius Jard Feb 08 '21 at 10:55
  • Hi @CaiusJard.. i have edited the question with where i am facing problem..also uploaded dataset and all files pic.. Also suggest how should i write the connection string as i am new to this and doing a project for my class. – Bhaskar Roy Feb 08 '21 at 11:11
  • *"`SqlCommand cmd = new SqlCommand("select * from [user] where Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text`"* THIS IS INCREDIBLY DANGEROUS (yes caps because I really am shouting that!). There are multiple problems here; You are storing passwords as plain text (massive issue), and it's wide open to injection. Fix your design, never inject values into your SQL like that, **parametrise**, and stop storing plain text passwords; salt and hash them. Someone could easily get into your system by entering their username as `' OR 1=1;--` and nothing for the password. – Thom A Feb 08 '21 at 11:45

2 Answers2

2

Throw your Connection class away, and pass the connection string to the DataAdapter. Don't bother opening or closing the connection; DataAdapter knows how to open a connection if it's closed

Put the connectionstring into the Settings

enter image description here

Use parameters

 private void loginBtn_Click(object sender, EventArgs e)
 {
    using(var sda = new SqlDataAdapter("select * from [user] where Username=@user and password=@pass", Properties.Settings.Default.ConStr)
    {
      //USE PARAMETERS
      sda.SelectCommand.Parameters.Add("@user", SqlDbType.VarChar, usernameTxt.Text.Length).Value = usernameTxt.Text;
      sda.SelectCommand.Parameters.Add("@pass", SqlDbType.VarChar, passwordTxt.Text.Length).Value = passwordTxt.Text.GetHashcode(); //DO NOT store your passwords in plain text!!

      var dt = new DataTable();
      sda.Fill(dt);
      if (dt.Rows.Count > 0)
      {
        MessageBox.Show("Login Successful", "Sucsess", 
          MessageBoxButtons.OK, MessageBoxIcon.Information);
        new dashboard().Show();
        this.Hide();
      }

   }
}

Use parameters

Just in case you missed it: USE PARAMETERS. Never again, in your life ever, should you concatenate a value into an SQL string. Ever. There is no reason to do it, and doing it will result in the software you create being hacked / you getting fired / both

Also, don't store passwords in plain text, ever. Salt and hash them. I've used string.GetHashcode() for demo purposes, which is not good but better than plaintext


Do the same thing to the not working code:

public void GetStudentsRecord()
{
    using(var sda = new SqlDataAdapter("Select * From [student]", Properties.Settings.Default.ConStr)){
      var dt = new DataTable();
      sda.Fill(dt);

      sdataGridView.DataSource = dt; 
    }
}
Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

this issue also confusing me a few days after the IT guy do some security settings to the SQL Server. i have an EntityFramework for the Web application and a desktop application. after i did some setting on the SQL Server, the Web application comeback to work, but the desktop still with issue. but i used the some connection string for the both application, it make no sense one is work but the other doesn't. then i searched a lot until i found some one said need add a port number 1433 after the $ServerName$DatabaseInstanceName,1433 at here http://www.windows-tech.info/15/9f6dedc097727100.php . after i added it. the exception became: System.Data.SqlClient.SqlException: Login failed for user 'domain\name-PC$'. then i found this link System.Data.SqlClient.SqlException: Login failed for user: System.Data.SqlClient.SqlException: Login failed for user it said need add Trusted_Connection=False;. the whole connection string should be like: data source=XXXXX\SQLSERVER,1433;initial catalog=XXXDB;user id=UserID;password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;

hope this answer will help the ones out off Generic exception: "Error: 26-Error Locating Server/Instance Specified)