My app.config file:
<configuration>
<connectionStrings>
<add name="MegaPixelBizConn"
connectionString="Data Source=PSHERATH-PC;Initial Catalog=MegaPixelBiz;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then I created DBConnection file:
class DBConnection
{
#region Database connection method
public SqlConnection Connect()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ToString();
try
{
conn.Open();
}
catch
{
}
return conn;
}
#endregion
}
this is my login form:
SqlCommand cmd;
DataSet ds = new DataSet();
DBConnection db = new DBConnection();
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (txtUserName.Text == "" || txtPassword.Text == "")
{
lblError.Visible = true;
lblError.Text = "*Enter UserName and Password";
//MessageBox.Show(" Enter UserName and Password .");
return;
}
else
{
string sql = "SELECT * FROM login_info WHERE userName = '" + txtUserName.Text + "' and password = '" + txtPassword.Text + "'";
cmd = new SqlCommand(sql, db.Connect());
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i == 1)
{
this.Hide();
Home hm = new Home();
hm.Show();
ds.Clear();
}
else
{
lblError.Text = "*Not Registered User or Invalid Name/Password";
//MessageBox.Show("Not Registered User or Invalid Name/Password");
txtPassword.Text = "";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But when my project run, this error come: "Object reference not set to an instance of an object." please give me a solution. I use all suitable references
try
It should work
Basing my answer on this solution, try:
Make sure you have a reference to
System.Configuration
as well.Also remember to close your
connection
.EDIT
Based on your new edit, try this for your code (Note I unfortunately can't test if this works due to my PC being broken).
This will help prevent against
SqlInjections
as well.