你调用的对象是空的。怎么修 [英] Object reference not set to an instance of an object. how to fix

查看:101
本文介绍了你调用的对象是空的。怎么修的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个例外更新鲜和困惑吗?



当我运行代码时遇到此异常如何解决?

i'am a fresher and confusing with this exception?

When i'm running the code getting this exception how to fix?

using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class checkingusername : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(IsPostBack)
        {
        SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Username.mdf;Integrated Security=True;User Instance=True");
        con.Open();
        string select = "select * from tblregistration where Username='" + TextBox1.Text + "'";
        SqlCommand cmdselect = new SqlCommand(select,con);
        int temp = Convert.ToInt32(cmdselect.ExecuteScalar().ToString());
        if (temp == 1)
        {
            Response.Write("UserId already Exists select other one");
        }
       
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Username.mdf;Integrated Security=True;User Instance=True");
        string insert = "insert into tblregistration(UserName,Password) values(@UserName,@Password);";
        SqlCommand cmdinsert = new SqlCommand(insert,con);
        cmdinsert.Parameters.AddWithValue("@UserName", TextBox1.Text);
        cmdinsert.Parameters.AddWithValue("@Password", TextBox2.Text);
        cmdinsert.Connection = con;
      
        con.Open();
        {
            try
            {
                cmdinsert.ExecuteNonQuery();
                con.Close();
                Response.Write("Data saved");
            }
            catch
            {
                Response.Write("Some thing Wrong");
            }
        }
    }
}

推荐答案

string select = "select * from tblregistration where Username='" + TextBox1.Text + "'";
       SqlCommand cmdselect = new SqlCommand(select,con);
       int temp = Convert.ToInt32(cmdselect.ExecuteScalar().ToString());



如果你在这里错误..



你得到所有选中的行字段请清楚你需要什么?

对于Get Single值然后使用这个


If you'r error here ..

you are getting all selected row field please do clear What you need?
For Get Single value then use this

int temp = Convert.ToInt32(cmdselect.ExecuteScalar()); 



对于整行值,然后使用DATATABLE OR DATASET(可选)


For whole Row values then use DATATABLE OR DATASET (optional)

DataTable dt = new DataTable()
 string select = "select * from tblregistration where Username='" + TextBox1.Text + "'";
SqlDataAdapter adap = new SqlDataAdapter(select,con); 
adap.Fill(dt);
int temp = Convert.ToInt32(dt.Rows[0]["Columnname"]);


这篇关于你调用的对象是空的。怎么修的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆