2011-04-25 71 views
0

我是C#的新手。我已經創建了登錄屏幕。我沒有能夠檢查用戶名和密碼。這是我的代碼。任何人都可以幫助我。請提前感謝。請不要猶豫,複製代碼。SQL連接對象上的空引用

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; 
using System.Data.Sql; 

    namespace Voting_Editor_Tool 
    { 
     public partial class Form1 : Form 
    { 
     SqlConnection cn; 
     public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 


    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     Application.Exit(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string username = txtusername.Text; 
     string password = txtpassword.Text; 

     if (ValidateUserNamePassword(username, password)) 
     { 
      // move to next form or do whatever you need to do after a successfull login 
     } 
     else 
     { 
      MessageBox.Show("Invalid user name or password", "Invalid Login"); 
      return; 
     } 
    } 
    public bool ValidateUserNamePassword(string _username, string _password) 
    { 
        // string connectionString = "Data Source=[servername];Initial       Catalog=[databaseName];User ID=[Admin Login];Password=[Admin Password];"; 

    using (SqlConnection cn= new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dish_tv;Data Source=ENMEDIA-CCDDFE5\ENMEDIA")); 
    { 
     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 valid 
      return true; 
     } 
     else 
     { 
      return false; 
     } 

     dr.Close(); 
     cn.Close(); 
    } 
     } 


    } 
    } 
+2

任何特定的錯誤? – V4Vendetta 2011-04-25 13:37:51

+2

與sa連接通常是一個壞主意。 – abhi 2011-04-25 13:39:40

+0

這是我得到的錯誤。對象引用未設置爲對象的實例。在行cn.Open(); – bharathi 2011-04-25 13:46:52

回答

2

刪除你的使用條款,並把這段代碼放入Try .. catch塊。捕捉異常對象並閱讀其stacktrace。仔細檢查連接字符串是否有任何輸入錯誤。這應該給你更多的細節來調試比一般的錯誤,如「對象引用未設置爲對象的實例」

+0

太棒了!感謝這個優秀的提示! – Bondt 2012-11-27 21:19:49

2

在使用語句的結尾處有一個分號,因此會終止使用。刪除分號,它將工作。

+0

它不起作用可以幫助你 – bharathi 2011-04-25 14:33:24

+0

你是否得到了不同的錯誤,或相同的位置/ – Leons 2011-04-25 14:35:27

相關問題