获取错误“对象引用未设置为对象的实例”。 [英] Getting the error "object reference not set to an instance of an object".
本文介绍了获取错误“对象引用未设置为对象的实例”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我提供代码..请解决错误。等待解决方案。
Im providing the code..Please solve the error. Waiting for the solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Default_login_trial : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
SqlCommand cmd = new SqlCommand("Login_Check_Sp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@username", txtUserName.Text.Trim());
cmd.Parameters.AddWithValue("@pwd", txtPwd.Text.Trim());
adp.SelectCommand = cmd;
adp.Fill(dt);
cmd.Dispose();
if (dt.Rows.Count > 0)
{
lblStatus.Text = "Login Successfull";
}
else
{
lblStatus.Text = "Wrong Username/Password";
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
dt.Clear();
dt.Dispose();
adp.Dispose();
}
}
}
推荐答案
试试这样
Try like this
protected void btnLogin_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("Login_Check_Sp", conn);
cmd.Parameters.AddWithValue("@username", txtUserName.Text.Trim());
cmd.Parameters.AddWithValue("@pwd", txtPwd.Text.Trim());
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
lblStatus.Text = "Login Successfull";
}
else
{
lblStatus.Text = "Wrong Username/Password";
}
}
}
如果你有错误,请尝试上面的代码。
调试a和使用断点检查你得到错误。
可能有很多原因因为连接可能没有建立。
这里有一些链接解释了如何在视觉工作室中使用断点。
http://www.tutorialspoint.com/asp.net/asp.net_debugging.htm [ ^ ]
https://www.youtube.com/watch?v=k1EQndVmlOc [ ^ ]
这篇关于获取错误“对象引用未设置为对象的实例”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文