I'm new to C# and im trying to make a login form at the start of an application that will connect to an SQL database. The error im getting is that it cannot make a connection to ANY database at all.
cn.Open() is returning the connection failure I used the example on this site :)
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespaceKronos
{
publicpartialclassForm1 : Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidLoginButton1_Click(object sender, EventArgs e)
{
string username = UserBox1.Text;
string password = PassBox1.Text;
if (ValidateUserNamePassword(username, password))
{
MessageBox.Show("Succsess!", "Authentication Complete");
}
else
{
MessageBox.Show("Invalid user name or password", "Invalid Login");
return;
}
}
publicboolValidateUserNamePassword(string _username, string _password)
{
string connectionString = "Server=localhost;Database=kronos;User ID=root;Password=;";
using (SqlConnection cn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "tsp_GetUserNameAndPassword";
SqlParameterCollection sqlParams = cmd.Parameters;
sqlParams.AddWithValue("@UserName", _username);
sqlParams.AddWithValue("@Password", _password);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
// this will return true if a row matching the username and password is found.// this means that the user's input is validreturntrue;
}
else
{
returnfalse;
}
dr.Close();
cn.Close();
}
}
}
}
Does anyone know why?
4 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Suthish NairRank #93 · 22.6K pointsPosted Oct 19, 2010, 12:28 PM EDT
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ToString())) { using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = con; con.Open(); //Add Parameteres here SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Console.WriteLine("{0}\t{1}", reader.GetInt32(0), reader.GetString(1)); } } else { Console.WriteLine("No rows found."); } reader.Close(); } }Josh Doust2 pointsPosted Oct 20, 2010, 1:44 AM EDT
Can you please explain how i would implement this code into my current project?
Thanks :)
Suthish NairRank #93 · 22.6K pointsPosted Oct 20, 2010, 2:59 AM EDT
rest of the codes are same from your given sample.
Suthish NairRank #93 · 22.6K pointsPosted Oct 24, 2010, 11:57 PM EDT