【发布时间】:2018-07-24 16:13:33
【问题描述】:
我想将日期存储到数据库。我单击文本框,它在日期之后显示日历,选择它存储到文本框螺母中,而不是存储在 Sql 数据库中。它显示一个错误
对象引用未设置为对象的实例
我的aspx页面代码:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="\GridMaster\Styles\">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true
});
});
</script>
<td class="dateBox">
<input type="text" id="datepicker" />
</td>
Aspx.cs 页面:
private void BindTextBoxvalues()
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from Student where RegNo=" + num, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
RegNo.Text = dt.Rows[0][0].ToString();
Name.Text = dt.Rows[0][1].ToString();
datepicker.Text = dt.Rows[0][2].ToString();//Object reference not set to an instance of an object
}
}
protected void Add_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd1 = new SqlCommand("sp", con);
cmd1.CommandType = CommandType.StoredProcedure;
con.Open();
cmd1.Parameters.AddWithValue("@RegNo", RegNo.Text);
cmd1.Parameters.AddWithValue("@Name", Name.Text);
cmd1.Parameters.AddWithValue("@DOB", datepicker.Text);//Object reference not set to an instance of an object
try
{
cmd1.ExecuteNonQuery();
Label2.Visible = true;
}
catch (Exception ex)
{
throw ex;
}
}
【问题讨论】:
-
您需要调试和检查,
dt.Rows[0][2]中出现的值是什么,应该是 null。因此,调用ToString会引发该错误。 -
是的,值为空。如何解决这个问题
-
检查 DB 为何返回 null。如果
Null很好,并且您想在 DB 返回 null 时显示一些内容,请将您的代码更改为:-dt.Rows[0][2]?.ToString() ?? "";(假设您使用的是 C# 6) -
请您更新我的代码以运行?
标签: javascript jquery asp.net sql-server sql-server-2005