List.Add 方法不起作用
本文关键字:不起作用 方法 Add List | 更新日期: 2023-09-27 18:35:34
public class abc
{
public abc(int ID, string Date, string jobtype, string command)
{
this.ID = ID;
this.Date = Date;
this.jobtype = jobtype;
this.command = command;
}
public int ID { get; set; }
public string Date { get; set; }
public string jobtype { get; set; }
public string command { get; set; }
}
public List<abc> getdata()
{
List<abc> data = new List<abc>();
SqlCommand cmd = new SqlCommand("SELECT * FROM [Table]",connection1);
using (connection1)
{
connection1.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
**data.Add(sdr["job_type"]);**
}
connection1.Close();
return data;
}
}
}
private DataTable Getdata(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = connection1;
try
{
connection1.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
connection1.Close();
sda.Dispose();
connection1.Dispose();
}
}
我的代码如上所述,我在数据上遇到错误。Add(sdr["job_type"]);哪里:
错误 2 "System.Collections.Generic.List 的最佳重载方法匹配有一些无效参数错误 3 参数 1:无法从"对象"转换为"WindowsFormsApplication1.Form1.abc"
我试图通过谷歌找到一些解决方案,但没有运气找到。我对 C# 很陌生,所以谁能告诉我我哪里做错了?代码是我在搜索过程中遇到的一些示例。
除了将数据库中的数据放在如上所示的列表中之外,还有其他方法吗?谢谢。
您必须
从数据库中读取的实际行创建一个新的abc
对象。
类似的东西
data.Add(new abc(
Convert.ToInt32(sdr["ID"]),
Convert.ToString(sdr["DATE"]),
Convert.ToString(sdr["job_type"]),
Convert.ToString(sdr["command"]))
);
不能简单地将数据库对象强制转换为abc
类。您需要读取每一列并创建一个新的abc
对象,因为您的列表只能包含对象abc
。
例如(我是根据MySQLReader知识这样做的,它可能有点不同)
while (sdr.Read())
{
data.Add(new abc((int)sdr["ID"],
(string)sdr["Date"],
(string)sdr["job_type"],
(string)sdr["command"]));
}
显然,列名需要重命名为确切的列名。
可能是这样的
您需要通过创建类对象来指定属性
data.Add(new abc() {job_type1=sdr["job_type"].ToString()});
或
将数据传递给类Abc
的构造函数
data.Add(new abc(sdr["job_type"].ToString()));
供参考
通过 MSDN
using (SqlDataReader sdr = cmd.ExecuteReader())
{
abc temp = new abc();
while (sdr.Read())
{
temp = new abc();
temp.ID = Convert.ToInt32(sdr["ID"]);
temp.Date = Convert.ToDate(sdr["Date"]);
temp.jobtype = Convert.ToString(sdr["job_type"]);
temp.command = Convert.ToString(sdr["command"]);
data.Add(temp);
}
connection1.Close();
return data;
}
我建议修改abc
的构造函数,使其将SqlDataReader
作为参数并在构造函数中执行赋值工作:
public class abc
{
private enum Column
{
ID = 1,
Date = 2,
jobtype = 3,
command = 4
}
public abc(SqlDataReader reader)
{
ID = sdr.GetFieldValue<int>[Column.ID];
Date = sdr.GetFieldValue<string>[Column.Date];
jobtype = sdr.GetFieldValue<string>[Column.jobtype];
command = sdr.GetFieldValue<string>[Column.command];
// or
//ID = (int)sdr["ID"];
//Date = (string)sdr["Date"];
//jobtype =(string)sdr["jobtype"];
//command = (string)sdr["command"];
}
public int ID { get; set; }
public string Date { get; set; }
public string jobtype { get; set; }
public string command { get; set; }
}
这样你的循环就很好很干净,解析/强制转换(如果有的话)封装了:
while (sdr.Read())
{
data.Add(new abc(sdr));
}