[英]My code line cannot work because of this error?
So basically here is the problem, I have tried many ways to fix it but none of them worked !所以基本上问题就在这里,我尝试了很多方法来解决它,但没有一个奏效! Error is getting at this line : Templist.Add((string)result["titre"];
. Templist
is the error !错误出现在这一行: Templist.Add((string)result["titre"];
Templist
是错误!
private List<string> ReadNews()
{
string SqlText = "SELECT * FROM nom_table";
List<string> Templist;
MySqlConnection SqlConnection = new
MySqlConnection(TheConnectionString);
MySqlCommand SqlCommand = new
MySqlCommand(SqlText,SqlConnection);
MySqlDataReader result = SqlCommand.ExecuteReader();
while (result.Read())
{
Templist.Add((string)result["titre"]);
}
return Templist;
}
Because you haven't initialized the Templist
, until you initialize/assign an instance the declared variable( Templist
) will be null, and you are not able to add something to null
that is what the error message says.因为您还没有初始化Templist
,所以在您初始化/分配一个实例之前,声明的变量( Templist
)将为空,并且您无法向null
添加一些内容,这就是错误消息所说的。 The code should be :代码应该是:
List<string> Templist = new List<string>();
One more thing I would like to add here is the usage of using
for proper disposal of the objects, and also specified column names
instead for *
.我想在这里添加的另一件事是使用using
正确处理对象,并指定column names
而不是*
。 Consider the modified snippets below:考虑以下修改后的片段:
private List<string> ReadNews()
{
string SqlText = "SELECT titre FROM nom_table";
List<string> Templist = new List<string>();
using (SqlConnection SqlConnection = new MySqlConnection(TheConnectionString))
{
using (MySqlCommand SqlCommand = new MySqlCommand(SqlText, SqlConnection))
{
using (MySqlDataReader result = SqlCommand.ExecuteReader())
{
while (result.Read())
{
Templist.Add((string)result["titre"]);
}
}
}
}
return Templist;
}
Your Templist
should be initialized before use.您的Templist
应在使用前初始化。 Change your declaration line to this:将您的声明行更改为:
List<string> Templist = new List<string>();
Templist is null, you haven't created an instance yet. Templist为空,您尚未创建实例。 Initialize:初始化:
List<string> Templist = new List<string>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.