如何从db收到我的信息到DataTable
?
我在DataTable
上有错误:"值不能为空。参数名称:dataTable"
public partial class _Default : System.Web.UI.Page
{
private DataTable dataTable;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connString);
string query = "select * from tbl_news";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
conn.Close();
da.Dispose();
}
}
答案 0 :(得分:3)
它告诉你先实例化DataTable
。
首次定义时,或者在方法本身中,您可以执行此操作...在尝试填充之前,只需将其设为。
dataTable = new DataTable();
da.Fill(dataTable);
不幸的是,如果DataTable
为null
,documentation没有说明它的作用。如果检查null
并在尝试填充之前对其进行实例化,那就太好了。
我挖到了程序集,那里肯定有代码检查null
,如果是,则抛出ArgumentNullException
。代码分布在几种方法中,但归结为:
if (dataTables == null)
{
throw new ArgumentNullException("dataTable");
}
答案 1 :(得分:1)
异常消息:
"值不能为空。参数名称:dataTable"
告诉您DataTable
为null
,且不得为null
。您无法填写不存在的表格。它是ArgumentNullException
,通常从方法抛出,以确保所需的传递参数不是null
。
要解决此问题,您只需初始化表格。
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dataTable = new DataTable();
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand("select * from tbl_news", conn))
using (var da = new SqlDataAdapter(cmd))
{
// no need to open the connection with DataAdapter.Fill
da.Fill(dataTable);
} // no need to close the connection with using-statement anyway
// do something with the table here, f.e. assign it as datasource
// for a webdatabound control like GridView
// ...
}
文档没有明确提及此异常,您可以找到它in the source。
为什么您不需要使用Fill
打开/关闭连接:
与SELECT语句关联的连接对象必须是 有效,但不需要打开。如果连接已关闭 在调用Fill之前,它会打开以检索数据,然后关闭。如果 在调用Fill之前连接已打开,它仍保持打开状态。
答案 2 :(得分:0)
首先像这样初始化数据表
DataTable dataTable = new DataTable();
然后填写
da.fill(dataTable);