Kate
Kate

Reputation: 945

Why I cannot connect to remote SQL server via C# application?

I am new to C# and I am using windows forms.

I have 2 computers connected together via Ethernet cross cable (no domain used) and they communicate successfully. PC1 has windows 7 and it hosts SQL server (192.168.10.1), PC2 has C# application which connects to SQL server, the C# application as following:

namespace Remote_DB_Connection
{
    public partial class Form1 : Form
    {
        SqlConnection MyConnection = new SqlConnection(@"Data Source=192.168.10.1\COFFEESHOP-PC,1433;Initial Catalog=mydb1;Trusted_Connection=True");

        SqlCommand MyCommand = new SqlCommand();
        DataTable DataTable = new DataTable();
        SqlDataAdapter Sql_Data_Adapter = new SqlDataAdapter();

        public Form1()
        {
            InitializeComponent();

            MyConnection.Open();
            MyCommand.CommandText = "SELECT * FROM Table1";
            MyCommand.Connection = MyConnection;
            Sql_Data_Adapter.SelectCommand = MyCommand;
            Sql_Data_Adapter.Fill(DataTable);

            button1.Text = Convert.ToString(DataTable.Rows[0]["Type"]);
            button2.Text = Convert.ToString(DataTable.Rows[1]["Type"]);
            button3.Text = Convert.ToString(DataTable.Rows[2]["Type"]);

            MyCommand.Parameters.Clear();
            Sql_Data_Adapter.Dispose();

            MyConnection.Close();
        }
    }
}

now, when I run the application it throws this error : "The login is from an untrusted domain and cannot be used with Windows authentication" . in the sql server I login using windows authentication.

I had a look here and here they said I should create a username and password in sql server to remotely connect to sql server. My question is: do I really have to create username and password in sql server to fix this error and connect to sql? I mean is there other ways to fix the issue?

Please help me, thank you

Upvotes: 3

Views: 996

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

My question is: do I really have to create username and password in sql server to fix this error and connect to sql?

Yes, because your machines are not part of a Windows Domain and Windows trusted authentication (Trusted_Connection=True) is not possible between them. If the machines are not part of a Windows Domain, SQL Server has no way of knowing who the client is unless it provides a username and a password in the connection string.

Upvotes: 3

Related Questions