DataTable dt = ds.tables[“put”]; why 'dt'

2019-03-06 02:20发布

问题:

This question already has an answer here:

  • What is a NullReferenceException, and how do I fix it? 31 answers
string sel = "select * from PUTIN";
DataSet ds = new DataSet();
DataTable dt = ds.Tables["put"];
DataRow row = dt.NewRow();

This is the code. When I run the line DataRow row = dt.NewRow(); I get an exception:

Object reference not set to an instance of an object

I find dt is null, why and how to slove it?

回答1:

Your DataSet is empty currently. You need to use a SqlDataAdapter here to fill your DataSet. Like this:

string sel = "select * from PUTIN";
SqlDataAdapter da = new SqlDataAdapter(sel,connection);
DataSet ds = new DataSet();
da.Fill(ds,"put");
DataTable dt = ds.Tables["put"];
DataRow row = dt.NewRow();