Reputation: 1
How can I receive my information from db into DataTable
?
I have an error on DataTable
: "Value cannot be null. Parameter name: 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();
}
}
Upvotes: 0
Views: 1396
Reputation: 460288
The exception message:
"Value cannot be null. Parameter name: dataTable"
tells you that the DataTable
is null
and must not be null
. You can't fill a table that doesn't exist. It Is an ArgumentNullException
which is typically thrown from a method to ensure that a required passed argument is not null
.
To fix it you just have to initialize the table.
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
// ...
}
The documentation does not mention this exception explicitly, you can find it in the source.
Why you don't need to open/close connections with Fill
:
The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
Upvotes: 1
Reputation: 66509
It's telling you to instantiate the DataTable
first.
You can do this when you first define it, or in the method itself... just make it is, before you try to fill it.
dataTable = new DataTable();
da.Fill(dataTable);
Unfortunately, the documentation doesn't say anything about what it does if the DataTable
is null
. It'd be nice if it checked for null
and instantiated it before trying to fill it.
I dug into the assembly, and there's definitely code in there that checks for null
, and throws an ArgumentNullException
if it is. The code is spread across several methods, but it boils down to:
if (dataTables == null)
{
throw new ArgumentNullException("dataTable");
}
Upvotes: 3
Reputation: 141
First initialize data table like this
DataTable dataTable = new DataTable();
Then fill it
da.fill(dataTable);
Upvotes: 0