DataTable dt = ds.tables[“put"];为什么'dt'为空?为空、ds、dt、DataTable

2023-09-06 04:43:21 作者:就风饮酒

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

这是代码.当我运行 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

我发现 dt 为空,为什么以及如何解决它?

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

推荐答案

您的 DataSet 目前为空.您需要使用 SqlDataAdapter 在这里填写您的 DataSet.像这样:

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();