Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从数据库中填充选项_C#_Sql Server_Database_Choice - Fatal编程技术网

C# 从数据库中填充选项

C# 从数据库中填充选项,c#,sql-server,database,choice,C#,Sql Server,Database,Choice,我想从数据库中的表中填写sList 我该怎么做 也许这会有帮助 SqlConnection cnn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from [Test]"; cnn.Open(); SqlDataAdapter adp = new SqlDataAdapter(cmd); Dat

我想从数据库中的表中填写
sList

我该怎么做

也许这会有帮助

SqlConnection cnn = new SqlConnection();

SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [Test]";

cnn.Open();

SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();

adp.Fill(ds);

Choices sList = new Choices();
1) 从属性中获取所需的表:

  Choices sList = new Choices();
  foreach (DataRow dr in ds.Table[0].Rows) {
    sList.Name = dr["name"]; // Or whatever your property is
  }
2) 创建一个方法,将每个
DataRow
转换为
Choices
列表中所需的类的实例(在本例中,我称之为
Choice
):

您可以在文档中了解如何从
DataRow
检索数据

3) 遍历行:

Choice DataRowToChoice(DataRow row)
{
    return new Choice() { Property1 = row["column1"] as string }; // ... etc.
}
可以找到
属性的文档

Choice DataRowToChoice(DataRow row)
{
    return new Choice() { Property1 = row["column1"] as string }; // ... etc.
}
foreach (var row in dataTable.Rows)
{
    sList.Add(DataRowToChoice(row));
}